下面的代码可能有助于解释如何在类中使用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()