调用实例或类方法,以适当的为准

时间:2019-04-02 22:22:34

标签: python

This question提到了一种用于区分实例方法(传递self)和静态方法(不传递任何东西)的技巧:

class X:
   def id(self=None):
      if self is None:
          # It's being called as a static method
      else:
          # It's being called as an instance method

(贷记Tom Swirly

但是,当继承开始起作用时,这很快就会成为一个问题,因为静态方法没有selfcls,因此无法在消息接收器上调用适当的方法。

我的问题是,我可以做这样的事情吗?

class X:
   def get(self_or_cls):
      if self_or_cls turns out to be cls:
          return self_or_cls.class_method()
      else:
          return self_or_cls.instance_method()


class Y(X):
   foo = str       

   @classmethod
   def class_method(cls):
       return cls.foo

   def instance_method(self):
       return self.foo()



>>> Y.get()
<class 'str'>
>>> Y().get()
''

感谢任何黑客!

1 个答案:

答案 0 :(得分:1)

this answer的帮助下,我为您找到了一种可能的破解方法:

class Custommethod:
    def __get__(self, ins, cls):
        if ins is None:
            return lambda : cls.class_method()
        else:
            return lambda : ins.instance_method()

class X:
   get = Custommethod()


class Y(X):
   foo = str       

   @classmethod
   def class_method(cls):
       return cls.foo

   def instance_method(self):
       return self.foo()


print(Y.get())  # <class 'str'>
print(Y().get())  # ''