使用父类的实例初始化子类

时间:2016-02-12 11:54:04

标签: python inheritance

假设我有一个班级:

class Person(object):

    def __init__(self, name, hobbies):

        self.name = name
        self.hobbies = hobbies

...(依此类推)

现在我想初始化一个扩展person的子类Employee。我想用Person类的实例初始化该类。所以我想这样做:

class Employee(Person):

    def __init__(self, person, salary):

        # Initialise the superclass from the given instance somehow
        # I know I could do: 
        super(Employee, self).__init__(person.name, person.hobbies)

        # But could I somehow do something like: 
        super(Employee, self).__init__(person)

        # (In this case the difference is small, but it could 
        # be important in other cases)

        # Add fields specific to an "Employee"
        self.salary = salary

然后我可以打电话:

p1 = Person('Bob', ['Bowling', 'Skiing'])
employed_p1 = Employee(p1, 1000)

我有什么方法可以做到这一点,或者我是否必须再次调用父类的构造函数?

非常感谢!

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

class Person(object):

    def __init__(self, name, hobbies):
        self.name = name
        self.hobbies = hobbies
    def display(self):
        print(self.name+' '+self.hobbies[0])

class Employee(Person):
    def __init__(self, a, b =None,salary=None):
        if b is None:
            self.person = a 
        else:
            self.person = Person(a,b)
        self.name = self.person.name
        self.hobbies = self.person.hobbies
        self.salary = salary


bob = Employee('bob',['Bowling', 'Skiing'])
bob.display()

sue1 = Person('sue',['photography','music'])
sue2 = Employee(sue1,salary=123)
sue2.display()

我已经添加了'显示'功能只是为了让它更容易遵循。希望这会有所帮助。