![](/img/trans.png)
[英]A method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it
[英]Check if a method is defined in the base or derived class
我想要一個函數來告訴我test
是基類的原始版本還是派生類中實現的新版本。 我發現inspect.getfullargspec
也許可以解決我的問題,但不適用於我的案例所需的Python 3。
class base_class(object):
@staticmethod
def test(a, b, c):
pass
class child_class(base_class):
@staticmethod
def test(a, b):
pass
class child_class_2(base_class):
pass
您不需要進行任何花哨的檢查即可:
>>> x = child_class_2()
>>> x.test
<function base_class.test at 0x7fea1a07f7b8>
>>> y = child_class()
>>> y.test
<function child_class.test at 0x7fea1a07f950>
默認情況下,打印的名稱來自該函數的__qualname__
屬性:
>>> x.test.__qualname__
base_class.test
>>> y.test.__qualname__
child_class.test
一種獲取類名的方法是
x.test.__qualname__[:-len(x.test.__name__) - 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.