Creating and initialising a Class in Python
To create an instance of a class ("to instantiate it") do
myObject = ClassName()
Where ClassName is the name of the class for which you want to create a new object.
myObject
will be an object of type ClassName
.
A class instance is often instantiated by passing parameters whose values are determined when the program is run. The values passed in as parameters are typically used by the functions in the class.
# Passing in a parameter when instantiating an object myObject = ClassName("A value")
Python uses the special function name __init__
for constructing a class with
parameters. This function always takes self
as the first parameter because the class constructor needs to know its own instance, just like
the class' functions.
class Animal(): def __init__(self, animal): self.animal = animal; def speak(self): if self.animal == 'Dog': print('woof') if self.animal == 'Cat': print('meow') animal1 = Animal('Dog') animal1.speak() animal2 = Animal('Cat') animal2.speak()
Output
woof meow
The self
Parameter
Notice that the definition of speak
has self
as a parameter,
but when we call speak
we don't pass in self
. The Python
inprepretor will always (quietly, in the background) pass a reference to the object
that called the function, to the function. This means speak
will have
animal1
(for example) passed into the method, and animal1
can be accessed via the self
parameter. Read more about
self
.