python - 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
吗?
解决方案
在实例级别
>>> 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)>
推荐阅读
- javascript - javascript 从 url 获取 html 内容(页面代码)
- kubernetes - 每次 Kubernetes 因资源使用而终止进程时,我如何记录?
- android - (Chromium for android studio) 如何使用 addPossiblyUnsafeJavascriptInterface?
- visual-studio - 在 url 中使用修改后的大小写更新服务引用不起作用
- hybris - Hybris:如何每小时触发一次 cronjob?
- c# - Azure 中没有“Access-Control-Allow-Origin”标头
- r - 将网站内容保存到 txt 文件中
- java - 如何使用警报触发器从应用程序向蓝牙模块发送值?
- c++11 - 如何将qt网络的pro文件转换为cmakelist
- php - 分解字符串然后创建数组