首页 > 解决方案 > Python - 确定类方法是否被覆盖或继承

问题描述

如果在实现过程中未将可能的覆盖标记为此类,是否有任何方法可以检查类方法是覆盖还是从基类继承?

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.method方法与或对它们的调用有什么区别Sub2.method可以区分它们是继承自的Super吗?

标签: pythoninheritance

解决方案


在实例级别

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

推荐阅读