Related
In Python, a constructor is a special method that gets called when an object of a class is created. Constructors are an important part of object-oriented programming and play a crucial role in initializing objects and performing setup tasks. In this guide, we'll cover everything you need to know about constructors in Python.
A constructor is a method that gets called when an object is created. It is responsible for initializing the object's properties and setting up any necessary state. In Python, the constructor method is called __init__
and takes at least one argument, which is self
. self
refers to the instance of the class that is being created.
Here's an example of a simple constructor in Python:
class MyClass:
def __init__(self):
print("Constructor called.")
When you create an object of this class, the constructor will be called automatically:
obj = MyClass() # prints "Constructor called."
You can also pass arguments to the constructor to initialize object properties. Here's an example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print(f"Person {name} created.")
In this example, we're creating a Person
class that takes two arguments: name
and age
. We're also printing out a message when the constructor is called. When you create a Person
object, you need to pass in the name
and age
arguments:
person = Person("John", 30) # prints "Person John created."
You can also use the constructor to initialize class variables. Class variables are variables that are shared by all instances of a class. Here's an example: