python - 在Python中,isinstance()可以用来检测类方法吗?

标签 python class-method isinstance

如何判断一个对象是否是类方法?使用 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/

相关文章:

python pillow(更好的PIL)编码检查bug

Python quantlib 示例?

python - Spark2-submit 对 python 字典进行意外的自动排序

ios - 在另一个 viewController 中调用类方法

ruby-on-rails - 如何为我的 Rails 模型创建自定义方法

java - 避免 isInstance 语句

Python 断言 isinstance() 向量

python - 我如何循环研究并搜索下一个数据

Python 相当于 Perl/Ruby ||=

Ruby 模块和扩展 self