作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何从非继承的另一个类访问变量?在我的代码中,我尝试使用 quickShot
中的 Ranger
对象从 Dragon
对象访问 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
最佳答案
我希望它看起来像:
class Character(object):
"""All Characters have a name and some hit points."""
def __init__(self, name, hit_points):
self.name = name # assigned in __init__ so instance attribute
self.hit_points = hit_points
class Player(Character):
"""Players are Characters, with added attack and defence attributes."""
def __init__(self, name, hit_points, attack, defence):
super(Player, self).__init__(name, hit_points) # call superclass
self.attack = attack
self.defence = defence
def _attack(self, other, chance, damage):
"""Generic attack function to reduce duplication."""
if random.random() <= chance:
other.hit_points -= damage # works for any Character or subclass
def quick_attack(self, other):
"""Attack with 80% chance of doing 10 damage."""
self._attack(other, 0.8, 10)
dragon = Character("Dragon", 25) # dragon is a Character instance
ranger = Player("Ranger", 100, 80, 50) # ranger is a Player instance
ranger.quick_attack(dragon)
print dragon.hit_points
解决这个问题,确保您了解正在发生的事情及其原因,然后在此基础上进行构建。如果你看不懂,我建议你寻找 Python OOP 教程(或 the official docs );你现在拥有的东西很快就会让你一事无成。
(另请注意奖金 style guide 合规性。)
关于python - 如何在 python 中使用另一个类的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26897868/
我是一名优秀的程序员,十分优秀!