Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

python - How to access outer attribute class within inner class?

I reconstruct my code to more readable by using class and follow javascript style. The class is about modem device. In below I have 2 inner classes, SMS and Identify. For now it focuss on retrieve device informations. The problem it got error

'Identify' object has no attribute 'handle'

Inner class can't access outer attribute class.

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

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

                print(buffer)

                if buffer == b'OK
':
                     break
                elif buffer == b'ERROR
':
                    break

device = Device()
device.open('COM12', 9600)
device.Identify().manufacturer()
device.close()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Identify doesn't inherit from Device just by being defined inside of it. If you want it to subclass Device, you need to explicitly write that:

class Identify(Device):
    . . .

The problem is though, a inner class can't inherit from an outer class. You'll need to make Identify a top level class along with Device.

class Device:
   . . .

class Identify(Device):
   . . .

If your intent was to make Identify slightly more hidden/indicate that it's an implementation detail, you could make it """private""" by giving the name a leading underscore:

class _Identify(Device):
   . . .

This doesn't actually prevent external access, but it does cause IDE warnings if it's imported or used externally, and causes it to be excluded from wildcard imports:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose names start with an underscore.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...