Lesson 36 of 4090%
(Progress persistence is disabled until Phase 9)
Python
Intermediate
Classes and Objects
Dive deeper into constructors and methods.
Classes and Objects
What You’ll Learn
You’ll learn how to initialize objects with data and create methods using self.
The __init__() Function
All classes have a function called __init__(), which is always executed when the class is being initiated (this is called the constructor).
Use the __init__() function to assign values to object properties.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name) # John
print(p1.age) # 36
What is self?
The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. It does not have to be named self (you can call it whatever you like), but it must be the first parameter of any function in the class.
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}")
p1 = Person("John", 36)
p1.greet() # Hello, my name is John