What is an object ()?

How is it possible that

class EmptyClass: def __init__(self): pass e = EmptyClass() ea = 123 

works and:

 o = object() oa = 123 

not ( AttributeError: 'object' object has no attribute 'a' ), but

 print isinstance(e, object) >>> True 

?

What is object() good if you cannot use it like that?

+6
source share
1 answer

You cannot add attributes to an object instance, because object does not have an __dict__ attribute (which will store the attributes). From docs :

class object

Return a new object without a lens. object is the base for all classes. It has methods that are common to all instances of Python classes. This function takes no arguments.

Note: object does not have __dict__ , so you cannot assign arbitrary attributes to an instance of the object class.

And object has its own capabilities:

  • As stated above, it serves as the base class for all objects in Python. Everything that you see and use ultimately depends on the object .

  • You can use object to create time zone values that are completely unique. Testing them with is and is not will only return True when the exact instance of object is specified.

  • In Python 2.x, you can (must) inherit from object to create a new style class. Classes of the new style have enhanced functionality and improved support. Note that all classes are automatically new-style in Python 3.x.

+12
source

Source: https://habr.com/ru/post/981936/


All Articles