如何访问内部类中的外部属性类?

时间:2019-12-01 20:55:11

标签: python

我通过使用class并遵循javascript样式来将代码重构为更具可读性。该类是关于调制解调器设备的。在下面,我有2个内部类,即SMS和Identify。目前,它专注于检索设备信息。出现错误的问题

'Identify' object has no attribute 'handle'

内部类无法访问外部属性类。

import serial

class Device:
    def open(self, port, baudrate):
        self.handle = serial.Serial(port, baudrate)

    def readline(self):
        return self.handle.readline()

    def close(self):
        self.handle.close()

    class SMS:
        pass

    class Identify:
        def manufacturer(self):
             self.handle.write(b'AT+CGMI\r')

             while True:
                buffer = self.handle.readline()

                print(buffer)

                if buffer == b'OK\r\n':
                     break
                elif buffer == b'ERROR\r\n':
                    break

device = Device()
device.open('COM12', 9600)
device.Identify().manufacturer()
device.close()

1 个答案:

答案 0 :(得分:2)

Identify不能仅从Device中进行定义而继承。如果希望它继承Device的子类,则需要明确地写成这样:

class Identify(Device):
    . . .

问题是inner class can't inherit from an outer class。您需要将IdentifyDevice一起设置为顶级课程。

class Device:
   . . .

class Identify(Device):
   . . .

如果您的意图是使Identify稍微隐蔽一些或表明它是实现细节,则可以通过在名称前加一个下划线将其命名为““ private”“”:

class _Identify(Device):
   . . .

这实际上并不能阻止外部访问,但是如果它是在外部导入或使用的,and causes it to be excluded from wildcard imports确实会引起IDE警告:

  

_single_leading_underscore:“内部使用”指标较弱。例如。从M import *不会导入名称以下划线开头的对象。

相关问题