用父类的实例初始化

用父类的实例初始化

本文介绍了用父类的实例初始化子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一堂课:

class Person(object):

    def __init__(self, name, hobbies):

        self.name = name
        self.hobbies = hobbies

...(依此类推)

现在,我想初始化一个子类Employee,它可以扩展人.我想用Person类的实例初始化该类.所以我想做:

Now I want to initialise a child class, Employee, which extends person. I would like to initialise that class with an instance of the Person class. So I would like to do:

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)

有什么办法可以做到这一点,还是必须显式地再次调用父类的构造函数?

Is there any way I can do this, or do I explicitly have to call the parent class's constructor again?

非常感谢!

推荐答案

我想你想要这样的东西:

I thnk you want something like this:

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

我添加了显示"功能,以使其易于使用.希望这会有所帮助.

I've added in the 'display' function just to make it easier to follow. Hope this helps.

这篇关于用父类的实例初始化子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:17