2016-02-12 118 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() 

只是爲了使其更易於遵循。希望這可以幫助。