我如何在 python 中执行构造函数重载?

How can i perform constructor overloading in python?

我有一个员工class,我想用两种不同的方式填写,并且想知道通过构造函数重载来做到这一点

class Employee:

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    def __init__(self, data):
        (self.first, self.last, self.pay) = data

这是因为,要么我必须像

那样初始化 class
Employee('John','Smith',3000)

或者我想通过传递像

这样的元组来初始化class
data = ('John','Smith',3000)
Employee(data)

你不知道,真的。您 可以 乱用

这样的定义
def __init__(self, *args):

然后进行大量处理,检查参数的数量、第一个参数的类型等。或者,您可以简单地显式定义一个 separate 构造函数,其名称准确描述了它的作用。 class 方法可以在将元组的内容传递给默认构造函数之前对其进行一些验证。

class Employee:
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @classmethod
    def from_tuple(cls, t):
        if len(t) != 3:
            raise ValueError("Wrong number of items in the tuple")

        return cls(*t)

data = ('John','Smith',3000)
Employee.from_tuple(data)

当然,class 方法定义的简单性表明您不需要这么麻烦:如果您知道元组具有正确的数量和类型的值,只需解压 data 与默认构造函数一起使用。

Employee(*data)

"default constructor" 是指 Employee.__new__ 解析到的方法。 Employee.__init__ 在技术上是一个 初始化器 ,在适当的时候在 __new__.

返回的已构造实例上调用