0

I am getting below error while accessing inner class __OnlyOne from outer. what is wrong here? I am trying to use a singleton design pattern here by creating only one instance of inner object to outer.

  Traceback (most recent call last):
  File "F:\parking_lot_code\test.py", line 25, in <module>
    PL.add_parking_floor('First Floor')
  File "F:\parking_lot_code\test.py", line 21, in add_parking_floor
    ParkingLot.instance.__parking_floors.append(floor)
AttributeError: '__OnlyOne' object has no attribute '_ParkingLot__parking_floors'

Process finished with exit code 1

Code

    class ParkingLot:
    instance = None

    class __OnlyOne:
        def __init__(self, name, address):
            self.__name = name
            self.__address = address
            self.__parking_floors = []

    def __init__(self, name, address):
        if not ParkingLot.instance:
            ParkingLot.instance = ParkingLot.__OnlyOne(name, address)
        else:
            ParkingLot.instance.__name = name
            ParkingLot.instance.__address = address

    def __getattr__(self, name):
        return getattr(self.instance, name)

    def add_parking_floor(self, floor):
        ParkingLot.instance.__parking_floors.append(floor)


PL = ParkingLot('Test Parking Lot', 'Bombay')
PL.add_parking_floor('First Floor')
myquest
  • 11
  • 5

2 Answers2

0

Use _ instead of __.

or use @property https://docs.python.org/ko/3/howto/descriptor.html

phi friday
  • 191
  • 4
0

In python, creating a function that starts with double underscore changes the name of the function to be _classname__methodname as described here - https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles

So try to use the "real name" or even better, don't use double underscore for "outside" use. If you do want to use double underscore, create a method that exposes it

  • i am new to OOPS in python, can you plz pin point the line and let me know what should be modified version of that as a sample. thanks – myquest Nov 21 '21 at 07:00
  • why i have a problem in using ParkingLot.instance.parking_floors.append(floor) but no problem in ParkingLot.instance.__name = name ParkingLot.instance.__address = address – myquest Nov 21 '21 at 07:05