gpt4 book ai didi

python - 如何在Python中检查派生自哪个类方法?

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:39 24 4
gpt4 key购买 nike

我有两门课:

class A(object):
def a(self):
pass

class B(A):
def b(self):
pass

print dir(A)
print dir(B)

如何检查 Python 中派生自哪些类方法?

例如:

getMethodClass(A.a) == A
getMethodClass(B.a) == A
getMethodClass(B.b) == B

最佳答案

有趣的问题。以下是我的做法。

(这在 python2 中有效。我还没有在 python3 中测试过它,但如果它不起作用我不会感到惊讶......)

您可以使用 reversed(inspect.getmro(cls)) 迭代所有“被提名者”,并返回第一个(通过获取迭代器的 next 值) ) 满足条件:它具有相关 attr,并且 attr 与相关 cls 的方法相同。

方法身份比较是通过比较未绑定(bind)方法的 im_func 属性来完成的。

import inspect

def getMethodClass(cls, attr):
return next(
basecls for basecls in reversed(inspect.getmro(cls))
if hasattr(basecls, attr)
and getattr(basecls, attr).im_func is getattr(cls, attr).im_func
)

getMethodClass(A, 'a')
=> __main__.A
getMethodClass(B, 'a')
=> __main__.A
getMethodClass(B, 'b')
=> __main__.B

# an alternative implementation, suggested by @chameleon
def getAttributeClass(cls, attrName):
# check first if has attribute
attr = getattr(cls, attrName)

mro = inspect.getmro(cls)
# only one class on list
if len(mro) == 1:
return cls

# many class on list
for base in reversed(mro[1:]):
# check if defined in this base
try:
baseAttr = getattr(base, attrName)
except AttributeError:
continue
else:
if baseAttr.im_func is attr.im_func:
return base
# define in top class
return cls

该函数还可以具有您建议的签名:

def getMethodClass(unbound_method):
cls = unbound_method.im_class
attr = unbound_method.__name__
# rest of implementation is the same as before...

getMethodClass(B.a)
=> __main__.A

关于python - 如何在Python中检查派生自哪个类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com