简体   繁体   English

Python中的实例变量是否必须在__init__方法中为类初始化?

[英]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.

相关问题 如何对在 __init__ 方法之外初始化的实例变量进行单元测试 - How to unit test instance variables initialized outside __init__ method 在`__init__()` 之外声明的实例变量在python 中有什么不同吗? - Do instance variables declared outside of `__init__()` have any differences in python? 如何在__init__中获取python类实例变量? - How to get python class instance variables inside __init__? 如何优雅/高效地为需要大量实例变量的 Python 类编写 __init__ 函数? - How do I elegantly/efficiently write the __init__ function for a Python class that takes lots of instance variables? python类的__init__方法 - __init__ method of python class python 如何处理 class 中的属性? 我是否总是必须在 __init__ 方法中初始化它们? - How does python handle attribute in a class ? Do I always have to initialize them in __init__ method? 在 python 类中使用密集的 __init__ 方法是一个好习惯吗? - Is it a good practice to have an intensive __init__ method in a python class? 为什么Python在实例创建时调用实例方法__init __()而不是调用类提供的__init __()? - Why doesn't Python call instance method __init__() on instance creation but calls class-provided __init__() instead? Python和__init__方法中的实例属性 - Instance attributes in Python and __init__ method 在__init__中更改时,python类变量可以成为实例变量吗? - Can python class variables become instance variables when altered in __init__?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM