What is object() good for?

后端 未结 1 1718
悲&欢浪女
悲&欢浪女 2021-02-05 12:34

How is it possible that

class EmptyClass:
    def __init__(self):
        pass

e = EmptyClass()
e.a = 123

works and:

o = objec         


        
相关标签:
1条回答
  • 2021-02-05 12:57

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

    class object

    Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.

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

    And object does have its uses:

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

    2. You can use object to create sentinel values which are perfectly unique. Testing them with is and is not will only return True when an exact object instance is given.

    3. In Python 2.x, you can (should) inherit from object to create a new-style class. New-style classes have enhanced functionality and better support. Note that all classes are automatically new-style in Python 3.x.

    0 讨论(0)
提交回复
热议问题