在python中,属性化对象能否访问其对象的其他属性?

2024-04-24 10:52:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,如果这太糟糕,我会提前道歉

假设我动态地使一个对象成为另一个对象的属性。 指定为属性的对象是否可以访问指定给对象的其他属性的,而无需继承作为参数传递

例如:

class human:
    def __init__(self):
        self.health = 100

class fire:
    def __init__(self):
        self.fire = 10
    def damage(self):
        ????.health -= self.fire   #can i do anything to get bill's health?

bill = human()
bill.fired = fire()
bill.fired.damage()   #the fired object wants to know the bill object's health

我知道我可以通过bill的健康作为损害函数的参数:-

class human:
    def __init__(self):
        self.health = 100

class fire:
    def __init__(self):
        self.fire = 10
    def damage(self, obj):
        obj.health -= self.fire

bill = human()
bill.fired = fire()

print bill.health

bill.fired.damage(bill)   #now the fired object knows bill's health

print bill.health   #works fine

但有没有其他办法,或者这是一条死胡同?除了遗产。 (我使用的是PythonV2.7,当然我也想知道v3解决方案)

如果这个问题太糟糕或者已经得到回答,我再次道歉。 我试着读这本书,但我听不懂,太复杂了。如果我用谷歌搜索这个问题,结果只会导致“如何访问对象属性”,例如这个https://www.geeksforgeeks.org/accessing-attributes-methods-python/。这个How to access attribute of object from another object's method, which is one of attributes in Python?使用继承


2条回答

是的,您可以在创建human时将其传递到fire,因为它们似乎彼此链接:

class Human:
    def __init__(self):
        self.health = 100

class Fire:
    def __init__(self, human):
        self.fire = 10
        self.human = human
    def damage(self):
        self.human.health -= self.fire

bill = Human()
bill.fired = Fire(bill)
bill.fired.damage()   #the fired object damages bill object's health

我不确定您的目标是什么,但正如我所提到的,您的问题在我看来像是一种代码气味(表明某些地方不正确)

假设您希望^ {< CD1>}实例着火(即创建^ {< CD2>}实例),然后推断火灾损害的健康状况,请考虑下面的重构:

class human:
    def __init__(self):
        self.health = 100
        self.fire = None

    def set_on_fire(self):
        self.fire = fire()

    def suffer_burn_damage(self):
        if self.fire is not None:
            self.health -= self.fire.damage

class fire:
    def __init__(self):
        self.damage = 10

bill = human()
print(bill.health)  # output: 100
bill.set_on_fire()
bill.suffer_burn_damage()
print(bill.health)  # output: 90

这样,您首先就不需要fire实例来了解human的运行状况。它的“工作”是跟踪它是否被烧毁,以及何时推断它自己的损失

这在更抽象的意义上也是有意义的——这也是使用OOP的要点之一。现实生活中的火有一定的能量。一个人一旦着火,他的“健康”就可以从火的能量中推断出来。火灾本身不需要知道人类的健康状况,也不需要知道其他任何事情

相关问题 更多 >