Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create class object without __dict__

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__?

like image 328
Damamaty Avatar asked Aug 09 '14 17:08

Damamaty


People also ask

What is Obj __ dict __?

object.__dict__ A dictionary or other mapping object used to store an object's (writable) attributes.

What is the __ dict __ attribute of an object in Python?

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.

What is __ slots __?

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__.

How to define a class in Python?

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.


1 Answers

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)
like image 139
Martijn Pieters Avatar answered Oct 12 '22 14:10

Martijn Pieters