How to call constructor from superclass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class User(object): def __init__(self, id_code, name, surname): self.id_code = id_code self.name = name self.surname = surname class Worker(User): def __init__(self, username, password, worker_type): super(User, self).__init__() self.username = username self.password = password self.worker_type = worker_type |
如何调用具有超级类属性的构造函数?
前任:
1 2 3 4 5 | id_code ="test_code" name ="test_name" surname ="test_surname" username ="test_username" password ="test_pass" |
首先,你有一个小的逻辑错误,@martijnpieers已经指出:
1 | super(Worker, self).__init__() |
为了将它们传递给超类,您需要在子类中接受这些参数。通过硬编码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class User(object): def __init__(self, id_code, name, surname): self.id_code = id_code self.name = name self.surname = surname class Worker(User): def __init__(self, id_code, name, surname, username, password, worker_type): # changed super(Worker, self).__init__(id_code, name, surname) # changed self.username = username self.password = password self.worker_type = worker_type |
或者使用
我会坚持硬编码的论点,只有当从长远来看这变得复杂时,我才会考虑切换到