简体   繁体   中英

python (2.7): Access class property using class decorator

I am trying to access an instance of a class (call it 'a'), which is passed to a second class (call it 'b'). My intention is to access instance 'a' by decorating instance b's class so that I can setup some background threading tasks on 'a', while still using 'b' for other more important tasks. Is this possible?

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)

The decorator was ill-formed

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

I am able to use the above decorator definition to access an instance of a class A (that is passed to class B)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM