Initializing class, __init__ ()
method
Many classes like to create objects with instances customized to a specific initial state.
__init__
is one of the many method names that have special significance in Python classes. Notice the double underscore both in the beginning and at the end in the name.
__init__
is short for "initialize", so it's also called initialization method. All classes should have an __init__()
method. When you create a new object of the class, Python automatically calls __init__()
right away to initialize the new object.
In previous Apple
class, it looks like we set the object's value by assigning values to the class variables(name = 'Fuji'
) when defining the class. Whenever a new Apple
object is created, it always set to be Fuji
But in fact, the standard way to initialize an object's values when creating objects is to use __init__( )
method in class.
Let's rewrite the Apple
class in a more standard way:
class Apple:
def __init__(self)
self.color = 'red'
def say(self):
print("I'm an apple.")
a1 = Apple() # create an Apple instance, a1
print(a1.color) # red
a1.say() # I'm an apple
Like all methods in a class, __init__()
always takes at least one argument (also the first argument), self
, which refers to the object itself being created.
Here in __init__()
, we define a variable using self.color
to indicate that color
is instance variable, it belongs to an object.
If a class defines an __init__()
method, when you create a class instance (an object), Python automatically calls __init__
function only once to initializing an object's variables.
So in this example, a1
is a new, initialized Apple instance, it has variable color
and has initial value 'red'
.
a1
also has a method a1.say()
that can print out message "I'm an apple."