gpt4 book ai didi

python - @classmethod 用于构造函数重载

转载 作者:行者123 更新时间:2023-12-01 01:44:29 26 4
gpt4 key购买 nike

我通常使用 isinstance 进行构造函数重载,但人们也建议使用 @classmethod 来实现相同的目的。但据我所知,@classmethod 共享该变量。

下面是一个简单的类

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

现在我有两个问题,

  • 是否可以使@classmethod不共享类变量?
  • 如何正确使用@classmethod进行构造函数重载?

最佳答案

也许您想先初始化实例,然后将类中的 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)

关于python - @classmethod 用于构造函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51541712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com