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

卡洛斯

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

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

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

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

任何黑客表示赞赏!

三亚什

这个答案的帮助下,我发现了一种可能的破解方法:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章