Python 中从子对象访问父对象数据成员

问题描述 投票:0回答:1

我有如下设置

class decorator:
    def __init__(self, fn):
        self.fn = fn

    @staticmethod
    def wrap(fn):
        return decorator(fn)

    def __call__(self):
        print(f"decorator {self} function called")


class A:
    @decorator.wrap
    def foo(self):
        print(f"Object {self} called")

    def __init__(self):
        self.boo = 'Boo'

如何从装饰器对象访问

boo
变量?

python decorator composition
1个回答
0
投票

解决方案可能涉及在装饰器中使用嵌套包装函数。

  1. 装饰器类:

decorator
类有一个静态方法
wrap
,它返回一个包装的嵌套函数。 当您调用用
@decorator.wrap
修饰的实例方法时,就会调用此包装函数。

  1. 访问
    boo
    变量:

wrapped
函数接受类的实例(即类A的
self
)作为其第一个参数。当调用实例方法(如
foo
)时,该实例引用类 A 的对象。 在包装函数内部,我们使用捕获的实例访问
boo
属性。

  1. 函数调用:

打印

boo
的值后,使用其参数调用原始方法(在本例中为
foo
),确保原始功能保持不变。

class decorator:
    def __init__(self, fn):
        self.fn = fn

    @staticmethod
    def wrap(fn):
        def wrapped(instance, *args, **kwargs):
            # Now we have access to instance (i.e., self for class A)
            print(f"decorator function called")
            print(instance.boo)
            return fn(instance, *args, **kwargs)
        return wrapped

class A:
    @decorator.wrap
    def foo(self):
        print(f"Object {self} called")

    def __init__(self):
        self.boo = 'Boo'

# Testing
a = A()
a.foo()  # This will print the decorator message, value of boo, and then the object message.

© www.soinside.com 2019 - 2024. All rights reserved.