gpt4 book ai didi

python - 如何在 python 中使用另一个类的变量?

转载 作者:行者123 更新时间:2023-11-30 23:18:09 25 4
gpt4 key购买 nike

如何从非继承的另一个类访问变量?在我的代码中,我尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com