@classmethod 用于构造函数重载

@classmethod for constructor overloading

我通常使用 isinstance 来重载构造函数,但人们也建议使用 @classmethod 来重载构造函数。但据我所知 @classmethod 共享变量。

下面是一个简单的class

class abc:
    def __init__(self, a=0):
        self.a = a    

    @classmethod
    def from_const(cls, b=30):
        cls.b = b
        return cls(10)

    def printme(self):
        print(self.a,self.b)

现在,让我们制作三个对象

a1 = abc(a=100)
a2 = abc.from_const(b=31)
a3 = abc.from_const(b=41)
a4 = abc().from_const(b=51)
a5 = abc().from_const(b=61)


a1.printme()
a2.printme()
a3.printme()
a4.printme()
a5.printme()

输出:

100 61
10 61
10 61
10 61
10 61

现在我有两个问题,

也许您想先初始化实例,然后将 class 中的 b 分配给它。

想法是这样的:

class abc:
    def __init__(self, a=0):
        self.a = a
        self.b = None

    @classmethod
    def from_const(cls, b=30):
        instance = cls(10)
        instance.b = b
        return instance

    def printme(self):
        print(self.a,self.b)

a1 = abc(a=100)
a2 = abc.from_const(b=31)
a3 = abc.from_const(b=41)
a4 = abc.from_const(b=51)
a5 = abc.from_const(b=61)

输出:

(100, None)
(10, 31)
(10, 41)
(10, 51)
(10, 61)