簡體   English   中英

如何在Python中從繼承的類設置和獲取父類屬性?

[英]How to set and get a parent class attribute from an inherited class in Python?

我有Family及其繼承的Person類。 如何從Person類中獲取familyName屬性?

class Family(object):
    def __init__(self, familyName):
        self.familyName = familyName

class Person(Family):
    def __init__(self, personName):
        self.personName = personName

例如,讓這些FamilyPerson對象:

strauss = Family('Strauss')
johaness = Person('Johaness')
richard = Person('Richard')

我想做一些事情,比如:

print richard.familyName

得到'Strauss' 我怎樣才能做到這一點?

你不能。

實例僅繼承父類方法和屬性,而不是實例屬性。 你不應該混淆兩者。

strauss.familyNameFamily實例的實例屬性。 Person實例將擁有自己familyName屬性副本。

您通常會將Person構造函數編碼為兩個參數:

class Person(Family):
    def __init__(self, personName, familyName):
        super(Person, self).__init__(familyName)
        self.personName = personName

johaness = Person('Johaness', 'Strauss')
richard = Person('Richard', 'Strauss')

另一種方法是Person持有對Family實例的引用:

class Person(object):
    def __init__(self, personName, family):
        self.personName = personName
        self.family = family

Person不再繼承Family 使用它像:

strauss = Family('Strauss')
johaness = Person('Johaness', strauss)
richard = Person('Richard', strauss)

print johaness.family.familyName

除了Martijns建議之外,您還可以從Family實例創建Person,這樣可以讓家人跟蹤它的成員:

class Person(object):
    def __init__(self, person_name, family):
        self.person_name = person_name
        self.family = family

    def __str__(self):
        return ' '.join((self.person_name, self.family.family_name))

class Family(object):
    def __init__(self, family_name):
        self.family_name = family_name
        self.members = []

    def add_person(self, person_name):
        person = Person(person_name, self)
        self.members.append(person)
        return person

    def __str__(self):
        return 'The %s family: ' % self.family_name + ', '.join(str(x) for x in self.members)

用法如下:

>>> strauss = Family('Strauss')
>>> johannes = strauss.add_person('Johannes')
>>> richard = strauss.add_person('Richard')
>>> 
>>> print johannes
Johannes Strauss
>>> print richard
Richard Strauss
>>> print strauss
The Strauss family: Johannes Strauss, Richard Strauss

暫無
暫無

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

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