Loading lesson path
The init() Method
init(), which is always executed when the class is being initiated.
init() method is used to assign values to object properties, or to perform operations that are necessary when the object is being created.
Create a class named Person, use the init() method to assign values for name and age: class Person:
def __init__(self, name, age):Formula
self.name = name self.age = age p1 = Person("Emil", 36)print(p1.name)
print(p1.age)init() method is called automatically every time the class is being used to create a new object. Why Use init()?
init() method, you would need to set properties manually for each object:
init()
class Person:
Formula
pass p1 = Person()p1.name = "Tobias"
p1.age = 25 print(p1.name)
print(p1.age)init() makes it easier to create objects with initial values:
init(), you can set initial values when creating the object: class Person:
def __init__(self, name, age):Formula
self.name = name self.age = age p1 = Person("Linus", 28)print(p1.name)
print(p1.age)
Default Values in __init__()You can also set default values for parameters in the init() method:
Set a default value for the age parameter: class Person:
def __init__(self, name, age=18):Formula
self.name = name self.age = age p1 = Person("Emil")
p2 = Person("Tobias", 25)print(p1.name, p1.age)
print(p2.name, p2.age)init() method can have as many parameters as you need:
Create a Person class with multiple parameters: class Person:
def __init__(self, name, age, city, country):Formula
self.name = name self.age = age self.city = city self.country = country p1 = Person("Linus", 30, "Oslo", "Norway")print(p1.name)
print(p1.age)
print(p1.city)
print(p1.country)