如何从另一个未继承的类访问变量?在我的代码中,我试图用quickShot
方法中的Ranger
对象访问hitPoints
类变量。在
class Dragon(object):
name = "Dragon"
hitPoints = 25
# Create the Ranger class
class Ranger(object):
name = "Ranger"
attack = 80
defence = 50
hitPoints = 100
def __init__(self):
self = self
def quickShot(self):
damage = 25
test = random.random()
if test < .8:
#I cannot access the dragon's hitPoints
Dragon.hitPoints = Dragon.hitPoints - damage
else:
pass
def concentratedShot(self):
damage = 50
chance = random.random()
if chance <= .5:
chance = True
else:
chance = False
def heartSeeker(self):
damage = 100
chance = random.random()
if chance <= .3:
chance = True
else:
chance = False
1)您需要创建一个Dragon类的实例,并将其传递给def quickShot(self):方法
或
2)您可以使用static variables使它们成为Dragon类本身的一部分。然后可以访问变量,而无需创建类的实例。在
显然,在你这个“龙与游骑兵的世界”这个例子中,第二个解决方案并不是最好的。在
我希望它看起来像:
解决这个问题,确保你明白发生了什么和为什么,然后继续努力。如果您不能遵循它,我建议您查找Python OOP教程(或the official docs);您现在所拥有的将不会让您快速获得任何好处。在
(注意还有奖金style guide合规性。)
我想你想要的是指定被射杀的龙。然后你可以在你的类中传递一个龙的实例。在
相关问题 更多 >
编程相关推荐