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:
- The
__new__method is called, which allocates memory for the new object. - Then, the
__init__method is called, which initializes the object by setting initial attribute values. - 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