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

标签 python decorator composition

我的设置如下

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 变量?

最佳答案

@S.B 的解决方案有效,但不是线程安全的,因为 A 的多个实例可能会在不同线程中同时调用 foo 方法,从而覆盖在调用源自另一个实例的 __call__ 方法之前装饰器对象的 instance 属性。

线程安全的方法是从 __get__ 方法返回一个包装函数,并通过闭包提供可用的实例:

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

    def __get__(self, instance, owner=None):
        def wrapper(*args, **kwargs):
            print(f'decorator {self} function called; boo = {instance.boo}')
            return self.fn(instance, *args, **kwargs)
        return wrapper

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

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

A().foo()

输出:

decorator <__main__.decorator object at 0x7f6ef3316c10> function called; boo = Boo
Object <__main__.A object at 0x7f6ef3339580> called

演示:Try it online!

关于python - Python中从子对象访问父对象数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77311656/

相关文章:

python - 检查 self.__class__ 的目的是什么?

python - 如何将带有斯堪的纳维亚字符的 UTF 字符串转换为 ASCII?

python - 类装饰器、继承、super() 和最大递归

objective-c - 使用组合而不是继承

Python SOAP 客户端 - 使用 SUDS 还是其他?

python - IOError : request data read error

javascript - 导轨 5/JavaScript : dynamically update only record attributes that have updated on page

python - 如何在单独的文件中获取函数的函数名称?

class - 领域类与实现类

language-agnostic - 更喜欢组合而不是继承?