1. 程式人生 > 其它 >在Python實現多個建構函式/構造方法

在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())