首页 > 解决方案 > 调用实例或类方法,以适当者为准

问题描述

这个问题提到了一种区分实例方法(传递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

汤姆斯威利的学分)

但是,当继承发挥作用时,这很快就会遇到问题,因为静态方法没有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()
''

任何黑客表示赞赏!

标签: python

解决方案


在此答案的帮助下,我为您找到了一种可能的技巧:

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())  # ''

推荐阅读