在Python实现多个构造函数/构造方法

原因:

python只允许一个init 函数构造类

法1:将init的参数改为不定长参数:

方法思路:
将__init__ 的参数改为不定长参数,
然后在__init__ 中通过判断参数的数量,进行不同的操作

class Rect:
    __length = 0
    __width = 0
# 使用不定长参数
    def __init__(self, *x):
        if len(x) == 1:
            self.__length = x[0]
            self.__width = x[0]
        elif len(x) == 2:
            self.__length = x[0]
            self.__width = x[1]

    def e(self):
        return self.__width * self.__length

# 正常使用
t = Rect(1)
print(t.e())
t = Rect(2, 4)
print(t.e())

法2: @classmethod 装饰器重载构造函数(推荐)

@classmethod 装饰器允许在不实例化类的情况下访问该函数。此类方法可以由类本身及其实例访问。当用于重载时,此类函数称为工厂方法。

我们可以使用他来实现 Python 中构造函数重载,使用看代码吧。

class Rect:
    __length = 0
    __width = 0

    def __init__(self, l, w):
        self.__length = l
        self.__width = w

    @classmethod
    def initsec(self, l):
       # 记得返回self
        return self(l, l)

    def e(self):
        return self.__width * self.__length

#使用方法和init不同
t = Rect.initsec(1)
print(t.e())
t = Rect(2, 4)
print(t.e())

posted @ 2022-06-01 20:07  kingwzun  阅读(6482)  评论(0编辑  收藏  举报