簡體   English   中英

屬性化的 object 能否訪問其對象在 python 中的其他屬性?

[英]Can an attributed object access its object's other attributes in python?

我是 python 的新手,如果這太糟糕了,請提前道歉。

假設我動態地使 object 成為另一個 object 的屬性。 分配為屬性object 是否可以在沒有inheritance作為參數傳遞的情況下訪問分配給對象的其他屬性?

例如:-

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

我知道我可以將比爾的健康作為損害 function 的論據:-

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

但是有沒有其他方法或者這是一個死胡同? 除了 inheritance。 (我正在使用 python v2.7,但當然也想知道 v3 解決方案)

如果這個問題太糟糕或已被回答,我再次道歉。 我試圖閱讀這個屬性可以訪問另一個屬性嗎? ,但我無法理解它,它太復雜了。 如果我用谷歌搜索這個問題,結果只會導致“如何訪問對象屬性”,例如這個https://www.geeksforgeeks.org/accessing-attributes-methods-python/ 而這個如何從另一個對象的方法訪問 object 的屬性,這是 Python 中的屬性之一? 使用 inheritance。

是的,你可以在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

我不確定您的目標是什么,但正如我所提到的,您的問題在我看來就像是代碼異味(表明某些事情不正確)。

假設您希望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 的要點之一。 現實生活中的火具有一定的能量。 着火的人的“健康”將從火所具有的任何能量中推斷出來。 火災本身與了解人類健康或其他任何事情無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM