class B(type):
__slots__ = ()
class A(metaclass=B):
pass
A.test = "test"
"A"
is instance of metaclass "B"
and "B"
have __slots__
defined - why I have __dict__
at class A
? How I can create class object without __dict__
?
object.__dict__ A dictionary or other mapping object used to store an object's (writable) attributes.
All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.
The __slots__ declaration allows us to explicitly declare data members, causes Python to reserve space for them in memory, and prevents the creation of __dict__ and __weakref__ attributes. It also prevents the creation of any variables that aren't declared in __slots__.
A class in Python can be defined using the class keyword. As per the syntax above, a class is defined using the class keyword followed by the class name and : operator after the class name, which allows you to continue in the next indented line to define class members. The followings are class members.
You cannot do this; classes always have a __dict__
.
You can only use __slots__
on classes to produce instances without a __dict__
, not on meta types. You'd normally only produce a few classes, so there is not much point in supporting __slots__
on metaclasses.
Don't use __slots__
to prevent attributes being set. Use __setattr__
for that instead:
class NoAttributesClassMeta(type):
def __setattr__(cls, name, value):
if name not in cls.__dict__:
raise AttributeError("Cannot set attributes")
type.__setattr__(cls, name, value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With