I've been getting into Python for a while now, since I'm still a beginner, I try to keep things simple as much as possible. There is however one thing that I would like to be able to do, but cannot get right.
I've searched and found several questions that somewhat resemble, mine, but answers are mostly to use eval() and exec(), which I read is very bad practice. Using a dictionary seems to be another often proposed option, but I don't see how to apply this to my case.
class pthead:
def __init__(self, name, port):
self.name = name
self.port = port
def initialize(self):
ser4.write(initialization_commands) # works
(self.port).write(initialization_commands) # doesn't work
UART.setup("UART4")
ser4 = serial.Serial(port="/dev/ttyO4", baudrate=9600, timeout=0.5)
head = pthead("kop", "ser4")
head.initialize()
Is it really that hard to use the variable as an object (hope I get the terminology right)? I can hardly believe it is not a common thing to do, for example after user input...
I'm using python 2.7 (for legacy purposes).
1 Answer 1
You are not using it correctly. The port you are supplying isn't a port but a string `"ser4".
class pthead:
def __init__(self, name, port):
self.name = name
self.port = port
def initialize(self):
self.port.write(initialization_commands) # it will work
if __name__ == "__main__":
UART.setup("UART4")
ser4 = serial.Serial(port="/dev/ttyO4", baudrate=9600, timeout=0.5)
head = pthead("kop", ser4) #supplying port as second argument
head.initialize()
6 Comments
x = pthead("name", ser4) returns "NameError: name 'ser4' is not defined"from foo import pthead and try to create an instance with x = pthead("name", ser4) I get the "NameError: name 'ser4' is not defined"error if I do not put quotes around the port.__init__ function should take name and a port value as argument but here you are essentially using port variable as argument
head = pthead("kop", ser4)it will work.