小编arr*_*nee的帖子

python如何从类体内部调用静态方法

假设我有一个带有静态方法的类,并且我希望将类属性设置为该方法返回的值:

class A:
    @staticmethod
    def foo():
        return 12

     baz = foo()
Run Code Online (Sandbox Code Playgroud)

但是这样做我得到一个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in A
TypeError: 'staticmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)

我找到了解决这个问题的方法:

class A:
    class B:
        @staticmethod
        def foo():
            return 2
baz = B.foo()
Run Code Online (Sandbox Code Playgroud)

但例如,如果我写:

class A:
    class B:
        @staticmethod
        def foo():
            return 2

    class C:
        baz = B.foo()
Run Code Online (Sandbox Code Playgroud)

我也收到一个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in …
Run Code Online (Sandbox Code Playgroud)

python static-methods class subclass class-method

3
推荐指数
1
解决办法
4189
查看次数

标签 统计

class ×1

class-method ×1

python ×1

static-methods ×1

subclass ×1