【问题标题】:How to access outer attribute class within inner class?如何访问内部类中的外部属性类?
【发布时间】:2019-12-01 20:55:11
【问题描述】:

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

'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()

【问题讨论】:

  • 为什么会一个Identify实例有一个handle属性?你期望它来自哪里?嵌套不是继承。
  • 在 Python 中使用“javascript 样式”是不合适的。使用 Python 风格。嵌套类在 Python 中的使用非常有限,当然在这里也没有。
  • @Carcigenicate 原因只是更具可读性。是的,我需要继承self.handle。就是这样。
  • @DanielRoseman 如果是这样,你有什么建议让这个概念在 python 中更具可读性?类识别需要从类设备处理。
  • 您的问题与可读性无关。如果您需要访问它,那么您需要使用组合,而不是嵌套。

标签: python


【解决方案1】:

Identify 不会继承自 Device 只是通过在其中定义。如果你想让它继承Device,你需要明确地写:

class Identify(Device):
    . . .

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

class Device:
   . . .

class Identify(Device):
   . . .

如果您的意图是让 Identify 稍微隐藏/表明它是一个实现细节,您可以通过在名称前面加上下划线来使其成为“”“私有”“”:

class _Identify(Device):
   . . .

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

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

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2015-06-09
    • 2014-08-10
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 2011-02-13
    相关资源
    最近更新 更多