【问题标题】:python (2.7): Access class property using class decoratorpython (2.7):使用类装饰器访问类属性
【发布时间】:2018-08-25 06:26:47
【问题描述】:

我正在尝试访问一个类的实例(称为“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)

【问题讨论】:

  • 认为我可以使用元类来完成这项工作,但我的印象是,如果可以使用继承来完成,我不应该使用这些。

标签: python class properties decorator


【解决方案1】:

装饰器格式不正确

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

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

【讨论】:

    猜你喜欢
    • 2014-02-08
    • 2012-06-02
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 2020-07-09
    • 2018-10-06
    • 2020-05-14
    • 2015-08-23
    相关资源
    最近更新 更多