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
Chat
Oh, the operator is not available. Leave us your comments. We will answer all your questions as soon as possible.
Anonymous
Καλησπέρα.
Καλησπέρα.
Anonymous
the infinteis -3/15 so 1triition / infinet
the infinteis -3/15 so 1triition / infinet
Anonymous
e
e
Anonymous
<a href="https://inspirum.pl "
<a href="https://inspirum.pl "
Anonymous
[url]https://inspirum.pl[/url]
[url]https://inspirum.pl[/url]
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e
LaceJaguar65
e
e