微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:如何装饰函数以将其更改为类方法

如何解决Python:如何装饰函数以将其更改为类方法

我有这样的代码,我想编写装饰器,它将装饰函数添加为类 A 的类方法

class A:
    pass

@add_class_method(A)
def foo():
    return "Hello!"

@add_instance_method(A)
def bar():
    return "Hello again!"

assert A.foo() == "Hello!"
assert A().bar() == "Hello again!"

解决方法

这种方法怎么样?
附注为了清晰起见,代码没有在结构上进行优化

from functools import wraps


class A:
    pass


def add_class_method(cls):
    def decorator(f):
        @wraps(f)
        def inner(_,*args,**kwargs):
            return f(*args,**kwargs)

        setattr(cls,inner.__name__,classmethod(inner))

        return f

    return decorator


def add_instance_method(cls):
    def decorator(f):
        @wraps(f)
        def inner(_,inner)

        return f

    return decorator


@add_class_method(A)
def foo():
    return "Hello!"


@add_instance_method(A)
def bar():
    return "Hello again!"


assert A.foo() == "Hello!"
assert A().bar() == "Hello again!"

,

这就是你想要的:

This is the incorrect date string format,try again fill the
,

在此处阅读docs

class MyClass:
    def method(self):
        # instance Method
        return 'instance method called',self

    @classmethod
    def cls_method(cls):
        #Classmethod
        return 'class method called',cls

    @staticmethod
    def static_method():
        # static method
        return 'static method called'

需要实例化 MyClass 才能到达(调用)实例方法

test = MyClass()
test.method()

可以直接访问类Method而无需实例化

MyClass.cls_method()
MyClass.static_method()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。