我有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'
。我怎么能这样做?
答案 0 :(得分:27)
你不能。
实例仅继承父类方法和属性,而不是实例属性。你不应该混淆这两者。
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
答案 1 :(得分:5)
除了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