一个方法可以用作static方法还是实例方法?

Jak*_*ake 5 python static-methods descriptor instance-methods

我希望能够这样做:

class A(object):
    @staticandinstancemethod
    def B(self=None, x, y):
        print self is None and "static" or "instance"

A.B(1,2)
A().B(1,2)
Run Code Online (Sandbox Code Playgroud)

这似乎是一个应该有一个简单解决方案的问题,但我无法想到或找到一个.

Ian*_* B. 9

有可能,但请不要.我忍不住实现了它:

class staticandinstancemethod(object):
     def __init__(self, f):
          self.f = f

     def __get__(self, obj, klass=None):
          def newfunc(*args, **kw):
               return self.f(obj, *args, **kw)
          return newfunc
Run Code Online (Sandbox Code Playgroud)

......及其用途:

>>> class A(object):
...     @staticandinstancemethod
...     def B(self, x, y):
...         print self is None and "static" or "instance"

>>> A.B(1,2)
static
>>> A().B(1,2)
instance
Run Code Online (Sandbox Code Playgroud)

邪恶!

  • 好样的!<clap> <clap> <clap>.现在鲨鱼只需要激光束. (2认同)