can a function be static and non-static in python 2

痞子三分冷 提交于 2019-12-20 06:13:44

问题


Lets say I have this class:

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

This would ideally in my world do this:

>>> Test.test(1,2)
3
>>> Test(1).test(2)
3

Now this doesn't work because you get this error:

TypeError: unbound method test() must be called with Test instance as first argument (got int instance instead)

In python3 this works fine, and I have the sneaking suspicion this is possible with a decorator in python2 but my python foo isn't strong enough to get that to work.

Plot Twist: So what happens when I need something on self when it's not called statically.


回答1:


If you want something that will actually receive self if called on an instance, but can also be called on the class, writing your own descriptor type may be advisable:

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)

Demo.

For the original version of your question, you could just write it like any other static method, with @staticmethod. Calling a static method on an instance works the same as calling it on the class:

class Test(object):
    @staticmethod
    def test(a, b):
        return a + b

Demo.



来源:https://stackoverflow.com/questions/47444780/can-a-function-be-static-and-non-static-in-python-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!