Can a method be used as either a staticmethod or instance method?

后端 未结 4 1795
遇见更好的自我
遇见更好的自我 2021-01-18 20:08

I\'d like to be able to do this:

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


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 20:52

    It is possible, but please don't. I couldn't help but implement it though:

    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
    

    ...and its use:

    >>> 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
    

    Evil!

提交回复
热议问题