属性对象可以在python中访问其对象的其他属性吗?

时间:2020-07-30 19:27:25

标签: python python-2.7 class oop object

我是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

我知道我可以将比尔的健康状况作为参数传递给损害函数:-

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

但是还有其他方法吗?或者这是死胡同?除了继承。 (我使用的是python v2.7,但当然也想知道v3解决方案)

如果这个问题太糟糕或已经回答,我再次道歉。 我尝试阅读此Can an attribute access another attribute?,但我听不懂,它太复杂了。而且如果我用谷歌搜索这个问题,结果只会导致“如何访问对象属性”,例如此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 个答案:

答案 0 :(得分:1)

是的,您可以在创建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 中,因为它们似乎相互链接:

url = "http://extreme-ip-lookup.com/json/" + fields[4]
function httpGet(Url)
{
   var xmlHttp = new XMLHttpRequest();
   xmlHttp.open( "GET", Url, false ); // false for synchronous request
   xmlHttp.send( null );
   return xmlHttp.responseText;
}
geographic_info = httpGet(url)
console.log(geographic_info)

答案 1 :(得分:0)

我不确定您的目标是什么,但是正如我所提到的,您的问题对我来说似乎是一种代码臭味(表明某些问题不正确)。

假设您希望human实例着火(即创建一个fire实例),然后推断出火灾对它们的健康造成了损害,请考虑以下重构:

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的运行状况。跟踪human的工作是跟踪它是否被燃烧以及何时推断其自身的损坏。

这在更抽象的意义上也是有意义的-这是使用OOP的要点之一。现实生活中的火灾具有一定的能量。着火的人将从其拥有的任何能量中得出其“健康”。火灾本身与人们的健康或与此有关的其他事情一无所知。