Python The __init__ Method
The __init__ method is a special method that runs when an object is made. __init__ gives the values at creation time.
Set values after creation
Each value takes its own line after the object is made.
class Dog:
pass
buddy = Dog()
buddy.name = "Buddy"
buddy.age = 3
print(buddy.name)
print(buddy.age)Set values at creation
__init__ runs as soon as Dog() runs. The given values land on self.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
print(buddy.name)
print(buddy.age)Each object keeps its own values
self is Buddy in the first call. self is Coco in the second call.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
coco = Dog("Coco", 2)
print(buddy.name)
print(coco.name)Starting values can change later
__init__ sets the starting value. It does not lock the value in place.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
buddy.age = 4
print(buddy.age)Example
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
coco = Dog("Coco", 2)
print(buddy.name)
print(buddy.age)
print(coco.name)
print(coco.age)Key points
- Method: a function that belongs to a class
- __init__: a special method that runs when an object is made
- self: the object that is being made or used
- Use self.name = name to store a value on the object
- Give the arguments after self in the same order at creation
- Python passes the new object for you.
In this example, Dog now has an __init__ method. Dog("Buddy", 3) makes an object and runs __init__ on it. Inside __init__, self is that new object. The lines store Buddy and 3 as its attributes. Dog("Coco", 2) then repeats the steps for a second object. Each dog keeps its own name and age.
Note
You never pass self yourself.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
In def __init__(self, name, age), what is self?