在Python 3中从类实例继承属性的正确方法是什么?
例如,如何从lastname
类的实例继承Family
等属性:
class Family:
def __init__(self, last):
self.lastname = last
class Person(Family):
def __init__(self, first):
self.firstname = first
# The below code does not work an is an example of the desired usage:
family = Family('Smith')
person = Person('David', family)
目标是让person
从lastname
类的family
实例继承Family
等属性:
>>> person.firstname
'David'
>>> person.lastname
'Smith'
答案 0 :(得分:0)
我认为你需要这样的东西:
class Family:
def __init__(self, last):
self.lastname = last
class Person(Family):
def __init__(self, first, family):
self.firstname = first
if isinstance(family, Family):
family = family.lastname
self.lastname = family
family = Family('Smith')
person = Person('David', family)
或者也许:
class Person(Family):
def __init__(self, first, family):
self.firstname = first
if isinstance(family, Family):
family = family.lastname
super().__init__(family)
答案 1 :(得分:0)
我看到两个选项:为person类实现def lastname(self)
并将实现推迟到存储的系列。
或者,您可以在此人身上实施__getattr__
并将所有内容转发给家人。我现在还不确定这种方法,它似乎与常规继承太相似了。例如。如果家庭有方法number_of_members(self)
,每个人也会拥有它。如果可以的话,常规继承也可以。