@classmethod用于构造函数重载 [英] @classmethod for constructor overloading

查看:136
本文介绍了@classmethod用于构造函数重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I usually use isinstance for constructor overloading, but people also suggests @classmethod for the same. But to my knowledge @classmethod shares the variable.

下面是一个简单的类

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

输出:

100 61
10 61
10 61
10 61
10 61

现在我有两个问题,


  • 是否有可能使@classmethod不共享类变量es吗?

  • 如何正确使用@classmethod进行构造函数重载?

推荐答案

也许您想先初始化实例,然后在类中为其分配 b

Maybe you want to init the instance first, then assign b inside your class to it.

这是一个主意:

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)

这篇关于@classmethod用于构造函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆