我想在一个类中使用self变量,并在另一个已经有自己的self变量的类中使用它们如何做到这一点。这里有一些代码可以提供帮助。
class A():
self.health = 5
class B(): # This class already has a self function
for sprite in all_sprites:
if pygame.sprite.collide_circle(self, sprite):
self.collide = True
self.health -= 0.1
你误会了。 self
只是一个内部参考。 在类中,您引用self
。 否则,您可以直接引用sprite
对象,
class A():
self.health = 5
class B(): # This class already has a self function
for sprite in all_sprites:
if pygame.sprite.collide_circle(self, sprite):
sprite.collide = True
sprite.health -= 0.1
下面的代码可能有助于解释如何在类中使用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()