函数可以是python 2中的静态和非静态函数

alb*_*jan 0 python python-2.x

让我们说我有这个课程:

class Test(object):
    def __init__(self, a):
        self.a = a

    def test(self, b):
        if isinstance(self, Test):
            return self.a + b
        else:
            return self + b
Run Code Online (Sandbox Code Playgroud)

理想情况下,在我的世界中这样做:

>>> Test.test(1,2)
3
>>> Test(1).test(2)
3
Run Code Online (Sandbox Code Playgroud)

现在这不起作用,因为您收到此错误:

TypeError: unbound method test() must be called with Test instance as first argument (got int instance instead)
Run Code Online (Sandbox Code Playgroud)

在python3中,这工作正常,我有一个潜行的怀疑,这可能与python2中的装饰器,但我的python foo不够强大,无法让它工作.

Plot Twist:当我不需要静态调用时,当我需要自己的东西时会发生什么.

use*_*ica 5

如果你想要self在实例上调用实际接收的东西,但也可以在类上调用,那么编写自己的描述符类型可能是可取的:

import types

class ClassOrInstanceMethod(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped
    def __get__(self, instance, owner):
        if instance is None:
            instance = owner
        return self.wrapped.__get__(instance, owner)

class demo(object):
    @ClassOrInstanceMethod
    def foo(self):
        # self will be the class if this is called on the class
        print(self)
Run Code Online (Sandbox Code Playgroud)

演示.

对于问题的原始版本,您可以像任何其他静态方法一样编写它@staticmethod.在实例上调用静态方法与在类上调用它的方法相同:

class Test(object):
    @staticmethod
    def test(a, b):
        return a + b
Run Code Online (Sandbox Code Playgroud)

演示.