Why are properties created that are not in Python class __slots__?

Asked 2 years ago, Updated 2 years ago, 59 views

class b():
    __slots__=['a']
    c=1


one=b()
one.a=1
try:
    one.b=2
except:
    print("Cannot be created")

print(one.a)



class q():
    pass

class w(q):
    __slots__=['a']

two=w()
two.a=1
two.b=2
print(two.a, two.b)

In class b, slots was specified so that only attribute a can be created Error occurs when creating other properties

However, the w class that inherits the q class also generates an attribute that is not in slots Why is it possible? slotsHow do I make an attribute without impossible to create?

class __slots__

2022-09-22 17:54

1 Answers

In Python, variables are managed as dict.

When you add a variable dynamically, __dict__ manages the variable as dict. Because this is mutable, you can put it dynamically.

However, if you use __slots__, remove __dict__. So you can't add it dynamically.

The problem is that the side effect is large. In addition to not being able to use the default function, vars, an error occurs if the external module requires __dict___ of the object.

The advantage of __slots__ is not to dynamically disable variables, but to save some performance and memory when there are many objects. Dynamic features are an advantage in dynamic language.

Let me tell you the answer.Inheritance requires __slots__ in all classes for parents and children. If you skip even one class after several steps of inheritance, you can't expect the desired action.

Personally, I think it's an unnecessary function compared to getting it (although it's beneficial to create many objects).

class q():
    __slots__=['a']

class w(q):
    __slots__=['b']


two=w()
two.a=1
two.b=2
#two.c=3    # error
print(two.a, two.b)

Vars(two) # Error missing __dict__
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute


There is no dir(two) # __dict__ and a and b are declared
['__class__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__slots__',
 '__str__',
 '__subclasshook__',
 'a',
 'b']


2022-09-22 17:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.