Skip to main content
 首页 » 编程设计

python之调用实例或类方法,以适当者为准

2024年11月24日10mate10pro

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 )

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

感谢任何技巧!

请您参考如下方法:

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