繁体   English   中英

Python - 确定类方法是被覆盖还是继承

[英]Python - Determine if class method is overriden or inherited

如果可能的覆盖在实现过程中没有被标记为这样,有没有办法检查类方法是覆盖还是从基类继承?

class Super(object):
  def method(self, x, y):
    v = x + y
    return v

class Sub1(Super):
  def method(self, x, y):
    v = x + y + 10 # the calcs are irrelevant, not a reliable way to determine if inherited
    return v

class Sub2(Super):
  def ownMethod(self):
    return 'something'

Sub1.methodSub2.method方法或对它们的调用有什么区别可以区分它们是从Super继承的吗?

在实例级别

>>> getattr(Sub1().__class__, 'method')
<function __main__.Sub1.method(self, x, y)>

getattr(Sub2().__class__, 'method')
>>> <function __main__.Super.method(self, x, y)>

在班级

>>> getattr(Sub1, 'method')
<function __main__.Sub1.method(self, x, y)>

>>> getattr(Sub2, 'method')
<function __main__.Super.method(self, x, y)>

我发现Sub2.method是完全一样的功能对象Super.method ,而Sub1.method是不同的对象:

>>> Sub2.method
<function Super.method at 0x7f9601345280>
>>> Super.method
<function Super.method at 0x7f9601345280>
>>> Sub2.method is Super.method
True
>>> Sub1.method is Super.method
False

所以如果你知道超类,你可以尝试像这样检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM