2

I found there is object() which is a built-in function in Python. *You can find object() in Built-in Functions

And, the documentation says below:

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

As the documentation says, object() can create an object but I don't know how to do it.

My questions:

2
  • 2
    From my understanding, object doesn't have a very practical use for the programmer, but rather, it is a function which can create the default object. The attributes and methods of this object can't be altered, but all parent classes created are, in reality, child classes of this object. It contains all the built-in class properties. The syntax is just my_obj = object() and I don't think it takes any parameters. Commented Nov 14, 2022 at 15:46
  • 1
    object is not a function; it's the root of Python's class hierarchy. (The documentation isn't clear on that point.) (It's possible that once upon a very long time ago, it really was a factory function that returned an instance of the root type, but I don't think that's been true since new-style classes were introduced in Python 2.2.) Commented Nov 14, 2022 at 15:58

2 Answers 2

2

To create an object with object, just call it: object(). However, it is never (as noted in the comments, it may be sometimes useful, when you need to have a something but you don't care what it is) used as is. object is just the (implicit in Python 3) base class of all classes. It provides basic features, such as allocation and magic methods, that you never directly manipulate in Python.

The naming follows one of Python's catchphrases "everything is an object".

Sign up to request clarification or add additional context in comments.

2 Comments

I wouldn't say "never". Direct instances of object are useful as sentinels when None is not appropriate.
@chepner edited accordingly.
0

You can create an object with only object() as shown below:

print(type(object()))

Then,the object of object class is created:

<class 'object'>

In addition, you can create and initialize the object of Person class with object() as shown below:

class Person:
    def __init__(self, name):
        self.name = name

obj = object().__new__(Person) # Creates the object of "Person" class
print(type(obj))

obj.__init__("John") # Initializes the object of "Person" class
print(obj.name)

Then, the object of Person class is created and initialized:

<class '__main__.Person'>
John

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.