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

时间:2017-05-30 08:58:51

标签: python class methods arguments 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)

我收到了这个错误:

TypeError: main_function() takes exactly 2 arguments (1 given)

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

1 个答案:

答案 0 :(得分:16)

如果您要创建的功能通常只需要绑定到特定类但不需要任何其他上下文,则只能使用@staticmethod。例如,str.maketrans() function是一种静态方法,因为它是您在处理字符串时经常使用的实用程序函数,将其命名为已存在的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)

您可以使用 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)

这有一个额外的好处,你可以使用继承。

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

import my_module

my_module.main_function(param1)

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

相关问题