Python | Classes
Start your free 7-days trial now!
A class serves as a general template for creating objects. A class serves to represent real-life things and situations. When we create an object from a class, this is referred to as instantiation.
Example
Below we have a very simple example of a class Cat
:
class Cat(): # This is constructor for python def __init__(self, name, age): self.name = name self.age = age # Teaching each cat how to meow def meow(self): print("I am a " + str(self.age) + " year old " + self.name)
# Creating an instance my_cat representing my cat Roxasmy_cat = Cat("Roxas", 26)my_cat.meow()
I am a 26 year old Roxas
The Cat
class above serves as a general template that tries to represent the general attributes and actions of all cats. Using this class we are able to easily create objects that represent ACTUAL cats such as my_cat
called Roxas
.
The convention is for classes to begin with a capital letter in Python.
The self
parameter is required in the method definition, and it must come first before the other parameters.
We do not have to pass the self
argument when instantiating my_cat
as this is passed automatically:
my_cat = Cat("Roxas", 26)
Every method call associated with a class automatically pass the self
argument. This is why we did not have to pass the self
argument when telling my_cat
to meow:
my_cat.meow()