如何从超类调用构造函数

时间:2016-05-01 15:14:42

标签: python oop

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

我如何使用超类的属性调用构造函数?

例如:

id_code = "test_code"
name = "test_name"
surname = "test_surname"
username = "test_username"
password = "test_pass"

1 个答案:

答案 0 :(得分:1)

首先你在那里遇到了一个小的逻辑错误@MartijnPieters已经指出:super的第一个参数应该是当前的类:

super(Worker, self).__init__()

为了将它们传递给超类,您需要在子类中接受这些参数。通过硬编码:

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

或使用*args**kwargs(参见例如:correct way to use super (argument passing))。但这远非琐碎,因为你需要知道哪个类需要哪个参数以及顺序应该如何以及哪些参数只是位置或仅关键字,或者如果你想将它们全部作为位置 - 或 - 关键字参数。你也隐藏了参数(-names)。

我会坚持使用硬编码参数,只有在长期考虑转换为*args, **kwargs时才会变得复杂。