简体   繁体   English

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

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

Is there any way to check if a class method is an override or inherited from base class if the possible override was not marked as such during implementation?如果可能的覆盖在实现过程中没有被标记为这样,有没有办法检查类方法是覆盖还是从基类继承?

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'

Would there be anything distinguishing about the methods Sub1.method vs Sub2.method or calls to them that would distinguish them as inherited from Super ? Sub1.methodSub2.method方法或对它们的调用有什么区别可以区分它们是从Super继承的吗?

At instance level在实例级别

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

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

At class level在班级

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

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

I found that Sub2.method is exactly the same function object as Super.method , while Sub1.method is a different object:我发现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

So if you know the superclass, you could try checking like this.所以如果你知道超类,你可以尝试像这样检查。

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

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