How do you pass an argument to a class constructor in Python?

Experience Level: Junior
Tags: Python

Answer

To define a constructor in a class, create a method with name __init__ and argument self. To pass additional arguments, add their names (and ideally even types) after the self argument, using a comma as a separator.

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

        print(f"Person {name} with age {age} was just created.")

Python for beginners
Python for beginners

Are you learning Python ? Try our test we designed to help you progress faster.

Test yourself