Sobes.tech
Junior — Middle

Can you explain how an object of a class is created in Python and what it means?

sobes.tech AI

Answer from AI

In Python, creating an object of a class is the process where we call the class as a function, and Python creates a new instance of that class.

When you write obj = MyClass(), the following happens:

  1. The __new__ method is called, which allocates memory for the new object.
  2. Then, the __init__ method is called, which initializes the object by setting initial attribute values.
  3. As a result, a ready object associated with the class is returned.

This means that an object is a specific instance of a class with its own state (attributes), which can be used to call methods and store data.

Example:

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

p = Person("Ivan")
print(p.name)  # Outputs: Ivan
Can you explain how an object of a class is created… - sobes.tech