如何设置和Python中继承的类获得一个父类的属性?(How to set and get a pa

2019-08-22 18:18发布

我有Family和继承的Person类。 我如何获得familyName从属性Person类?

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' 。 我怎样才能做到这一点?

Answer 1:

你不能。

情况下,仅继承父类的方法和属性,而不能访问实例属性。 你不应该将两者混为一谈。

strauss.familyName是一个实例属性Family实例。 该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


Answer 2:

除了Martijns建议,您也可以从家庭实例创建人,这样让家人保持它的成员跟踪:

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


文章来源: How to set and get a parent class attribute from an inherited class in Python?