Python中@staticmethod的意义是什么? [英] What's the point of @staticmethod in Python?

查看:31
本文介绍了Python中@staticmethod的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've developed this short test/example code, in order to understand better how static methods work in 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()

此代码运行正常,不会返回任何错误.我的问题是:

This code works correctly, it doesn't return any errors. My questions are:

  1. 我是否正确理解self"可以理解为此方法将从实例中调用"之类的东西?

  1. Do I understand correctly that "self" can be understood as something like "this method will be called from an instance"?

再说一次,@staticmethod 背后的逻辑是什么 - 是创建可以从实例调用的静态方法吗?这不正是静态方法的意义所在吗?

Then again, what's the logic behind @staticmethod - is it to create static methods which can be called from an instance? Isn't that exactly not what static methods are about?

为什么第二种方法比第三种更受欢迎?(我假设因为装饰器存在,所以有一点.)第三个选项似乎更简单,更直接.

Why would the second approach be favored over the third one? (I assume that since the decorator exists, there is a point to this.) The 3rd option seems to be the simpler and more straightforward.

推荐答案

这是一篇关于 静态方法.总结:

Here is a post on static methods. In summary:

  • 实例方法:需要实例作为第一个参数
  • 类方法:要求类作为第一个参数
  • 静态方法:不需要作为第一个参数
  • instance methods: require the instance as the first argument
  • class methods: require the class as the first argument
  • static methods: require neither as the first argument

关于您的问题:

  1. 是的.虽然变量名 self 是一个约定,但它与实例有关.
  2. 静态方法可用于将相似的实用方法归为同一类.
  3. 对于类中的方法,您要么需要添加 self 作为第一个参数,要么用 @staticmethod 修饰方法.没有参数的非修饰方法"会引发错误.
  1. Yes. While the variable name self is a convention, it pertains to the instance.
  2. Static methods can be used to group similar utility methods under the same class.
  3. For methods within a class, you either need to add self as the first argument or decorate the method it with @staticmethod. "Non-decorated methods" without arguments will raise an error.

当使用参数调用时,看看这些是如何工作的可能会更清楚.修改后的例子:

It may be more clear to see how these work when called with arguments. A modified example:

class TestClass:

    weight = 200                             # class attr 

    def __init__(self, size):
        self.size = size                     # instance attr

    def instance_mthd(self, val):
        print("Instance method, with 'self':", self.size*val)

    @classmethod
    def class_mthd(cls, val):
        print("Class method, with `cls`:", cls.weight*val)

    @staticmethod
    def static_mthd(val):
        print("Static method, with neither args:", val)

a = TestClass(1000)

a.instance_mthd(2)
# Instance method, with 'self': 2000

TestClass.class_mthd(2)
# Class method, with `cls`: 400

a.static_mthd(2)
# Static method, with neither args: 2

总的来说,你可以从访问的角度考虑每种方法:

Overall, you can think of each method in terms of access:

  • 如果您需要访问实例或实例组件(例如实例属性),请使用实例方法,因为它传递 self 作为第一个参数.
  • 同样,如果需要访问类,请使用类方法.
  • 如果对实例和类的访问都不重要,您可以使用静态方法.

请注意,在上面的示例中,为每个方法类型传递了相同的参数,但对实例和类属性的访问分别通过 selfcls 不同.

Notice in the example above, the same argument is passed for each method type, but access to instance and class attributes differ via self and cls respectively.

注意,有一种方法可以通过使用 self.__class__ 从实例方法访问类组件,从而不需要类方法:

Note, there is a way to access class components from an instance method by using self.__class__, thereby obviating the need for a class method:

    ...

    def instance_mthd2(self, val):
        print("Instance method, with class access via `self`:", self.__class__.weight*val)
    ...

a.instance_mthd2(2)
# Instance method, with class access via `self`: 400

REF:我建议观看 Raymond Hettinger 的 talk Python 的类开发工具包,通过示例清楚地阐明了每种方法类型的目的.

REF: I recommend watching Raymond Hettinger's talk Python's Class Development Toolkit, which elucidates the purpose for each method type clearly with examples.

这篇关于Python中@staticmethod的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆