Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 不是方法的python类中的函数_Python 2.7 - Fatal编程技术网

Python 2.7 不是方法的python类中的函数

Python 2.7 不是方法的python类中的函数,python-2.7,Python 2.7,我有一个需要辅助函数的类,例如,一个只使用传入参数而不使用类的任何属性来计算校验和的类。此函数仅由类的方法调用。因此,我不需要将“self”作为函数的第一个形式传递 我应该如何实现这些功能?类中可以有非方法函数吗?我是否应该在类之外定义它们(即使它们没有被其他任何东西使用)?或者它们可以作为常规方法吗?如果希望在类中使用不以self为参数的函数,请使用@staticmethod装饰器: class Awesomeness(object): def method(self, *args

我有一个需要辅助函数的类,例如,一个只使用传入参数而不使用类的任何属性来计算校验和的类。此函数仅由类的方法调用。因此,我不需要将“self”作为函数的第一个形式传递


我应该如何实现这些功能?类中可以有非方法函数吗?我是否应该在类之外定义它们(即使它们没有被其他任何东西使用)?或者它们可以作为常规方法吗?

如果希望在类中使用不以self为参数的函数,请使用
@staticmethod
装饰器:

 class Awesomeness(object):
     def method(self, *args):
         pass

     @staticmethod
     def another_method(*args):
         pass

但是,从概念的观点来看,我肯定会考虑把它放在模块范围内,特别是如果它是一个不使用实例或类属性的校验和函数。< /P> < P>只做嵌套函数:

class Foo(object):
    def bar(self, arg):
        def inner(arg):
            print 'Yo Adrian imma in inner with {}!'.format(arg)

        inner(arg)    

Foo().bar('argument')      
或者忽略
自身

class Foo(object):

    def prive(_, arg):
        print 'In prive with {}!'.format(arg)


    def bar(self, arg):
        def inner(arg):
            print 'Yo Adrian imma in inner with {}!'.format(arg)

        inner(arg)   
        self.prive(arg)

    def foo(self,arg):
        self.prive(arg)     

Foo().bar('argument')
Foo().foo('another argument') 
第二个示例打印:

Yo Adrian imma in inner with argument!   
In prive with argument!
In prive with another argument!

不幸的是,asker暗示它被多个方法使用。想要在类中定义回调函数,这个解决方案对我来说很有效。添加self参数而不使用它有什么不好?你为什么恨自己?@yuvi:-)是的,这很公平,我只是觉得这可能是一种不好的习惯或行为something@spiderplant0:模块范围本质上是表示全局的另一种方式。这是您自己提出的选项之一,定义“类外”函数。