首页 > 解决方案 > 需要另一个静态方法的 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

标签: python

解决方案


使用@classmethod装饰器函数将表示它不会更改实例中的任何内容,而您可以通过第一个参数访问该类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

推荐阅读