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)
有什麼辦法,我可以做到這一點,或者我明確必須再次調用父類的構造函數?
非常感謝!
你會這樣做'emp = Employee(Person('Bob','bowling'))'...? – deceze
對不起,你想用父類的實例做什麼?如果你需要一個Person()的實例,只需要明確地使用'some_person = Person(....)'。如果你想讓'Person .__ init __()'運行,使用'super().__ init __(some_name,some_hobbies)''。 –
但是,如果您已經傳遞了一個名爲'person'的參數,那麼無論何種調用Employee()都有責任提供該參數。 –