Editor settings

General settings

Save settings

Learn to program with Python

Methods that accept arguments #

Just like regular functions, class methods can accept arguments. In the previous lesson, we saw that you can define a string with the class str with an input argument, like so:

sentence = str("This is a sentence")
print(sentence) # Output: This is a sentence

To allow class construction to accept arguments, we can add more parameters to the __init__ method. For example:

class Car:
    def __init__(self, brand, year):
        print("A new car is created")
        print(f"The brand is {brand}")
        print(f"The year is {year}")

car = Car("Yotoya", 1990)
# Output:
A new car is created
The brand is Yotoya
The year is 1990

In the example above, we add 2 more parameters to the construction method: brand and year. When we create a new object from the Car class, we need to provide the arguments for those parameters, just like a regular function, with the exception that the first parameter, self, is automatically provided by Python.


Exercise #

  • Update the __init__ method in the Person class to accept arguments.

Tests #

  • Person("Abbey", 30) should print the message "Abbey is 30 years old"
  • Person("Eric", 40) should print the message "Eric is 40 years old"
Output will be displayed here