[英]Do instance variables in Python have to be initialized in the __init__ method for a Class?
Why is it if I don't set self.ser = False
first, I cannot pass around the self.ser
variable as a handle to write with pyserial
? 如果我没有先设置
self.ser = False
,为什么不能将self.ser
变量作为用pyserial
编写的句柄传递呢?
import serial
import time
class TestClass(object):
def __init__(self, port='/dev/ttyUSB0', baud=9600):
self.baud = baud
self.port = port
self.ser = False
def connect(self):
"""Opens serial connection to Device"""
self.ser = serial.Serial(self.port, self.baud, timeout=.5)
def writeuart(self, message):
self.ser.flushInput()
self.ser.write(message)
time.sleep(1)
return self.ser.read(self.ser.inWaiting())
So in other words, can I not create self.ser
from within the connect()
method and then make use of self.ser
in other methods of the same class? 因此,换句话说,我不能在
connect()
方法中创建self.ser
,然后在同一类的其他方法中使用self.ser
吗?
def __init__(self, port='/dev/ttyUSB0', baud=9600):
self.baud = baud
self.port = port
self.connect() # it's ok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.