python:如何修饰函数以将其更改为类方法

zwghvu4y  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(364)

我有这样的代码,我想写装饰将添加decorded函数作为类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!"
xzv2uavs

xzv2uavs1#

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

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(_, *args,**kwargs):
            return f(*args,**kwargs)

        setattr(cls, inner.__name__, 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!"
nfzehxib

nfzehxib2#

这就是你想要的:

class A:
    def __init__(self):
        pass

    @classmethod
    def foo(cls):
        return "Hello!"

    def bar(self):
        return "Hello again!"

print(A.foo())
print(A().bar())
k97glaaz

k97glaaz3#

在此处阅读文档

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()

您可以直接访问类方法,而无需示例化

MyClass.cls_method()
MyClass.static_method()

相关问题