问题
I usually use isinstance
for constructor overloading, but people also suggests @classmethod
for the same. But to my knowledge @classmethod
shares the variable.
Below is a simple 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)
Now, lets make three objects
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()
The output:
100 61
10 61
10 61
10 61
10 61
Now I have two questions,
- Is it possible to make @classmethod not share class variables ?
- How to properly use @classmethod for constructor overloading ?
回答1:
Maybe you want to init the instance first, then assign b
inside your class to it.
Here's the idea :
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)
Output:
(100, None)
(10, 31)
(10, 41)
(10, 51)
(10, 61)
来源:https://stackoverflow.com/questions/51541712/classmethod-for-constructor-overloading