我有Family
和继承的Person
类。 我如何获得familyName
从属性Person
类?
class Family(object):
def __init__(self, familyName):
self.familyName = familyName
class Person(Family):
def __init__(self, personName):
self.personName = personName
举例来说,让这些Family
和Person
的对象:
strauss = Family('Strauss')
johaness = Person('Johaness')
richard = Person('Richard')
我想要做的事情,例如:
print richard.familyName
并获得'Strauss'
。 我怎样才能做到这一点?
你不能。
情况下,仅继承父类的方法和属性,而不能访问实例属性。 你不应该将两者混为一谈。
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
除了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?