I have a following code but I want to transform it into module.
Obviously if I miport this code as module ser_r and ser will never be initialized and the Agent class won't work.
#module.py
class Agent:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def send(self, data):
message = data + ' ' + a
ser.write(message)
ser_r = serial.Serial(
port='COM6',
baudrate=500000,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser = io.TextIOWrapper(io.BufferedRWPair(self.ser_raw, self.ser_raw, 1),
newline='\r',
line_buffering=True)
So I came up with the idea to create class Serial which has ser variable which is then used in Agent class.
But now there is another problem: How do I access Serial inside Agent without creating instance of Serial? The user can create a Serial instance but then I don't know the name I should use inside Agent. I can make init method and then create Serial class inside. After importing user would call init method and then he could use it.
#module.py
class Agent:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def send(self, data):
message = data + ' ' + a
Serial.ser.write(message)
class Serial:
ser_r = serial.Serial(
port='COM6',
baudrate=500000,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser = io.TextIOWrapper(io.BufferedRWPair(self.ser_raw, self.ser_raw, 1),
newline='\r',
line_buffering=True)