@classmethod for constructor overloading

主宰稳场 提交于 2020-01-05 06:37:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!