bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Python/Object-Oriented Python
Python•Object-Oriented Python

Python __init__() Method

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Python init() Method?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Order

Put the learning moves in the order that makes the concept easiest to apply.

Default Values in __init__()
Why Use __init__()?
The __init__() Method

The __init__() Method

All classes have a built-in method called init() , which is always executed when the class is being initiated.

The init() method is used to assign values to object properties, or to perform operations that are necessary when the object is being created.

__init__()

Note

The init() method is called automatically every time the class is being used to create a new object.

Why Use __init__()?

Without the init() method, you would need to set properties manually for each object:

__init__()

Using init() makes it easier to create objects with initial values:

__init__()

Default Values in __init__()

You can also set default values for parameters in the init() method:

Example

class Person:
  def __init__(self, name, age=18):
    self.name = name
    self.age = age
    p1 = Person("Emil")
    p2 = Person("Tobias", 25)
    print(p1.name, p1.age)
    print(p2.name, p2.age)

Multiple Parameters

The init() method can have as many parameters as you need:

Example

class Person:
  def __init__(self, name, age, city, country):
    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)

Previous

Python Classes and Objects

Next

Python self Parameter