2016-02-12 84 views
0

假设我有一个类:与父类的实例初始化子类

class Person(object): 

    def __init__(self, name, hobbies): 

     self.name = name 
     self.hobbies = hobbies 

......(依此类推)

现在我想初始化一个子类,员工,延伸人。我想用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) 

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

非常感谢!

+0

你会这样做'emp = Employee(Person('Bob','bowling'))'...? – deceze

+0

对不起,你想用父类的实例做什么?如果你需要一个Person()的实例,只需要明确地使用'some_person = Person(....)'。如果你想让'Person .__ init __()'运行,使用'super().__ init __(some_name,some_hobbies)''。 –

+0

但是,如果您已经传递了一个名为'person'的参数,那么无论何种调用Employee()都有责任提供该参数。 –

回答

0

我thnk你想是这样的:我已经在“显示”功能添加

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

只是为了使其更易于遵循。希望这可以帮助。