需要另一个静态方法的Python类静态方法

可以有多个相互调用的静态方法吗?

就像是:

class Myclass():
    def __init__(self, a):
        self.var = self.static1(a)

    @staticmethod
    def static1(i):
        i += 1
        return self.static2(i)

    @staticmethod
    def static2(i):
        return i * 3

c = Myclass(1)

我有 :

NameError: name 'self' is not defined
评论
  • zipsum
    zipsum 回复

    use the @classmethod decorator function will denote it does not change anything in the instance while you can access the class via first parameter cls

    class Myclass():
        def __init__(self, a):
            self.var = self.static1(a)
    
        @classmethod
        def static1(cls,i):
            i += 1
            return cls.static2(i)
    
        @staticmethod
        def static2(i):
            return i * 3
    
  • uautem
    uautem 回复

    No need to prepend with 'self.'. Just call MyClass.static2(i)