I am trying to create a class (MySerial
) that instantiates a serial object so that I can write/read to a serial device (UART). There is an instance method that is a decorator which wraps around a function that belongs to a completely different class (App
). So decorator is responsible for writing and reading to the serial buffer.
If I create an instance of MySerial
inside the App
class, I can't use the decorator instance method that is created from MySerial
.
I have tried foregoing instance methods and using class methods as explained in this second answer, but I really need to instantiate MySerial
, thus create an instance using __init__
.
How can this be accomplished? Is it impossible?
- Create a decorator that is an instance method.
- Use this decorator within another class
class MySerial():
def __init__(self):
pass # I have to have an __init__
def write(self):
pass # write to buffer
def read(self):
pass # read to buffer
def decorator(self, func):
def func_wrap(*args, **kwargs):
self.write(func(*args, **kwars))
return self.read()
return func_wrap
class App():
def __init__(self):
self.ser = MySerial()
@self.ser.decorator # <-- does not work here.
def myfunc(self):
# 'yummy_bytes' is written to the serial buffer via
# MySerial's decorator method
return 'yummy_bytes'
if __name__ == '__main__':
app = App()