python获取类函数的变量不包括_python在另一个已经有self函数的类中获取自变量...

下面的代码可能有助于解释如何在类中使用self。注意在第45行,self被传递给sprite类的collide方法。在类内部,如果需要,可以将self(它表示当前正在处理的实例)传递给任何其他实例方法或函数。在import math

import random

def main():

b = B(5, 5, 2)

print('Health =', b.health)

b.collide_sprites()

print('Health =', b.health)

class Sprite:

def __init__(self, x, y, radius):

self.x = x

self.y = y

self.radius = radius

def collide(self, other):

middle_distance = math.hypot(self.x - other.x, self.y - other.y)

edge_margin = self.radius + other.radius

return middle_distance < edge_margin

class A(Sprite):

def __init__(self, x, y, radius):

super().__init__(x, y, radius)

self.health = 5

class B(A):

def __init__(self, x, y, radius):

super().__init__(x, y, radius)

self.all_sprites = [A(

random.randrange(10),

random.randrange(10),

random.randint(1, 4)

) for _ in range(50)]

self.collide = False

def collide_sprites(self):

for sprite in self.all_sprites:

if sprite.collide(self):

self.collide = True

self.health -= 0.1

if __name__ == '__main__':

main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值