如何判断一个对象是否是类方法?使用 isinstance()
不是最佳实践吗?如何实现这一点?
class Foo:
class_var = 0
@classmethod
def bar(cls):
cls.class_var += 1
print("class variable value:", cls.class_var)
def wrapper(wrapped: classmethod):
"""
Call the wrapped method.
:param wrapped (classmethod, required)
"""
wrapped()
Foo.bar()
wrapper(Foo.bar)
print("the type is:", type(Foo.bar))
print("instance check success:", isinstance(Foo.bar, classmethod))
输出:
class variable value: 1
class variable value: 2
the type is: <class 'method'>
instance check success: False
Process finished with exit code 0
最佳答案
如果您只想区分类方法与常规方法和静态方法,那么您可以使用 inspect.ismethod(f)
进行检查。
class A:
def method(self): pass
@classmethod
def class_method(cls): pass
@staticmethod
def static_method(): pass
在 REPL 中:
>>> from inspect import ismethod
>>> ismethod(A.method)
False
>>> ismethod(A.class_method)
True
>>> ismethod(A.static_method)
False
如果您更喜欢使用 isinstance
执行此操作,则可以使用 typing.types.MethodType
:
>>> from typing import types
>>> isinstance(A.method, types.MethodType)
False
>>> isinstance(A.class_method, types.MethodType)
True
>>> isinstance(A.static_method, types.MethodType)
False
请注意,这些测试将错误地识别例如A().method
因为实际上我们只是测试绑定(bind)方法而不是未绑定(bind)函数。因此,上述解决方案仅在假设您正在检查 A.something
的情况下才有效,其中 A
是一个类,而 something
是常规方法、类方法或静态方法。
关于python - 在Python中,isinstance()可以用来检测类方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70310274/