0

I have a simple class in here:

class Info: 
    # __slots__ = ('name','age')
    def __init__(self, name, age): 
        self.name = name 
        self.age = age

    def members(self):
        print(self.__dict__)

>>> Info(name= "John", age=10).members()
>>> {'name': 'John', 'age': 10}

Now, I add the __slot__ to the above class:

class Info: 
    __slots__ = ('name','age')
    def __init__(self, name, age): 
        self.name = name 
        self.age = age

    def members(self):
        print(self.__dict__)

Info(name= "John", age=10).members()

Now, I keep getting the following error. How am I be able to access objects attributes in this case? Thanks!

print(self.__dict__)
AttributeError: 'Info' object has no attribute '__dict__'
armin
  • 591
  • 3
  • 10
  • 2
    Right that's literally the purpose of `__slots__`. Removing `__dict__` makes objects considerably smaller, so you add a `__slots__` attr on objects you expect to instantiate hundreds or thousands of times – Adam Smith Jun 11 '21 at 04:52
  • [... `__slots__` reserves space for the declared variables and prevents the automatic creation of `__dict__` ...](https://docs.python.org/3.8/reference/datamodel.html?highlight=__slots__#object.__slots__) – Timus Jun 11 '21 at 07:52

0 Answers0