次のコードは、クラスでself
の使用方法を説明するのに役立つことがあります。 4539行目のself
は、スプライトクラスの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()
「自己機能」とは何ですか? – wim
'B'のインスタンスが' A'のインスタンスの 'health'属性を変更できるようにしたいのですか? – snakecharmerb
'self'はインスタンスを参照するための変数です。あなたのクラスは何を表していますか? –