Python:是否可以使用类自己的方法初始化类变量?

我想知道是否可以使用通过此类的@classmethod初始化的类变量来定义Python类。以下代码失败,但解释了我的意思:

class foo:
    a = 1
    b = 2
    c = foo.add(a,b)  # NameError: name 'foo' is not defined
    # c = a + b        # <-want to achieve this,but it duplicates add(),# which is what I want to avoid

    @classmethod
    def add(cls,x,y):
        return x+y

也尝试了c = add(a,b)但得到了TypeError: 'classmethod' object is not callable

有人知道吗?任何建议将不胜感激。

iCMS 回答:Python:是否可以使用类自己的方法初始化类变量?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/1919085.html

大家都在问