如何在类及其方法中使用self参数,@ staticmethod关键字

Sta*_*ess 4 python methods arguments class self

我有一个python类,它有多个方法.我已经通过@staticmethod实例定义了我的方法,我想从我的main函数(main_function)中调用我的类的其他方法.我想我需要self从我的main函数调用我的其他函数的参数,并且我想main_function在创建我的类的实例时将此参数传递给我.

class myclass:
  @staticmethod
  def function1(param1)
      print "function1"
  @staticmethod
  def main_function(self, param1)
     function1(param1)

my_object = myclass()
my_object.main_function(param1)
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误:

TypeError: main_function() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)

问题是我self在创建实例时没有参数.我尝试@staticmethod从我的方法定义中删除关键字并删除所有self参数,但这不起作用.

Mar*_*ers 20

@staticmethod在创建通常要与特定类绑定但不需要任何其他上下文的函数时使用.例如,该str.maketrans()函数是一个静态方法,因为它是一个在处理字符串时经常使用的实用函数,将它指向已经存在的str类型(它预先存在为类)的命名空间是有意义的.

您似乎将类用作命名空间.不要那样做.使用模块执行功能,您不必担心适用于类的特殊范围规则.只有在需要将状态功能捆绑在一起时才使用类.

如果你仍然坚持使用静态方法的类,那么你仍然难以在任何地方硬编码类名:

class myclass:
    @staticmethod
    def function1(param1)
        print "function1"

    @staticmethod
    def main_function(param1)
        # Want to use other functions in this class? Then you will
        # have to use the full name of the class as a prefix:
        myclass.function1(param1)
Run Code Online (Sandbox Code Playgroud)

您可以使用classmethods,因此您可以引用类对象:

class myclass:
    @staticmethod
    def function1(param1)
        print "function1"

    @classmethod
    def main_function(cls, param1)
        # Now you can use the `cls` reference to access other attributes
        cls.function1(param1)
Run Code Online (Sandbox Code Playgroud)

这具有额外的优势,您可以使用继承.

但是,使用模块是将一组函数组织到命名空间中的正确方法.将所有内容放入my_module.py包中的文件中,然后使用导入;

import my_module

my_module.main_function(param1)
Run Code Online (Sandbox Code Playgroud)

现在,my_module中的所有全局变量都捆绑在一个模块对象中,不需要前缀或cls引用.

  • @Martijin,这是一个非常好的答案.这对我帮助很大,我通过这个理解静态方法和模块.谢谢. (2认同)