使用Class实例而不是Classes的类继承

时间:2017-01-29 07:24:55

标签: python-3.x class oop inheritance

在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)

目标是让personlastname类的family实例继承Family等属性:

>>> person.firstname
'David'
>>> person.lastname
'Smith'

2 个答案:

答案 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),每个人也会拥有它。如果可以的话,常规继承也可以。