小编rbr*_*rtk的帖子

Python中@staticmethod的意义是什么?

我开发了这个简短的测试/示例代码,以更好地了解静态方法在Python中的工作方式。

class TestClass:
    def __init__(self, size):
        self.size = size

    def instance(self):
        print("regular instance method - with 'self'")

    @staticmethod
    def static():
        print("static instance method - with @staticmethod")

    def static_class():
        print("static class method")


a = TestClass(1000)

a.instance()
a.static()
TestClass.static_class()
Run Code Online (Sandbox Code Playgroud)

该代码正常工作,不会返回任何错误。我的问题是:

  1. 我是否正确理解“自我”可以理解为类似于“将从实例中调用此方法”?

  2. 再说一遍,@ staticmethod背后的逻辑是什么?是否可以创建可以从实例调用的静态方法?不就是没有什么静态方法是什么?

  3. 为什么第二种方法比第三种方法更受青睐?(我假设装饰器存在,所以有一点要注意。)第三个选项似乎更简单,直接。

python static-methods

5
推荐指数
1
解决办法
2015
查看次数

标签 统计

python ×1

static-methods ×1