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()都有责任提供该参数。 –