python (2.7):使用类装饰器访问类属性

居民

我正在尝试访问一个类的实例(称为“a”),该实例被传递给第二个类(称为“b”)。我的意图是通过装饰实例 b 的类来访问实例 'a',以便我可以在 'a' 上设置一些后台线程任务,同时仍然使用 'b' 执行其他更重要的任务。这可能吗?

import threading    
import inspect

Class doStuff():
    def __init__(self, somePropertyFromAnotherClass):
        self.lock = threading.Lock()
        self.prop = somePropertyFromAnotherClass

    def doCoolThreadingStuff():
        print("do threading stuff with {}".format(self.prop))


def someDecorator(cls):
    def wrapper(cls):
        print(inspect.getrgspec(cls.__init__))
        #ds = doStuff()  ## this is the bit that i can't figure out!
    wrapper(cls)
    return cls


Class A():
    def __init__(self):
        self.obj = "i'm an object" 


@someDecorator
Class B():
    def __init__(self, obj):
        self.obj = obj

    def doSomethingWithObj():
        print('doing something with obj')


if __name__ == "__main__":
    a = A()
    b = B(a)
居民

装饰器格式错误

def someDecorator(cls_obj):
    def wrapper(*args):
        ds = doStuff(args[0]) # positional : / 
        ds.doCoolThreadingStuff() 
        return cls_obj(*args)
    return wrapper

我可以使用上面的装饰器定义来访问 A 类的实例(传递给 B 类)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

类的Python装饰器

来自分类Dev

在python备注装饰器类中设置get / set属性

来自分类Dev

在python中使用类变量调用装饰器

来自分类Dev

装饰器如何与python中的类一起使用

来自分类Dev

Python类属性装饰器不起作用

来自分类Dev

用于类属性的python全局装饰器

来自分类Dev

私人成员可使用angular 2装饰器访问

来自分类Dev

从类更改组件装饰器Angular 2的属性

来自分类Dev

Python:在基类中使用派生类属性

来自分类Dev

将装饰器应用于访问类属性的类方法

来自分类Dev

访问类属性作为装饰器参数

来自分类Dev

使用属性装饰器的python类中的属性行为

来自分类Dev

在python类属性内访问`super()`

来自分类Dev

无法访问python超类属性

来自分类Dev

在python中的类方法上使用装饰器设置类的属性

来自分类Dev

Python:使用装饰器更改类类型并保留其方法

来自分类Dev

用于类属性的python全局装饰器

来自分类Dev

访问基类函数装饰器中的派生类属性

来自分类Dev

python2中的类方法挂钩装饰器

来自分类Dev

Python 3 使用装饰器生成错误与 Python 2

来自分类Dev

在 Python 中使用 django 访问类属性

来自分类Dev

使用装饰器添加类属性

来自分类Dev

在python中使用属性装饰器期间在init中赋值

来自分类Dev

如何从 Python 中的类中访问类属性

来自分类Dev

Python:使用@property装饰器时直接访问属性的setter方法

来自分类Dev

对 Python 类中的相关属性使用 @property 装饰器

来自分类Dev

Python 2.7 - 使用类作为计时和记忆的装饰器

来自分类Dev

在python的主类中使用子类属性

来自分类Dev

在类 python3 中使用装饰器