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.")
Related Python job interview questions
What is a private method in Python?
Python JuniorWhy would you use a private method in Python?
Python JuniorHow do you define a constructor in a class in Python?
Python JuniorWhat is a convention to name a protected method in Python?
Python JuniorWhat is a convention to name a private method in Python?
Python Junior