Python | Classes
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.
Below we have a very simple example of a class
class Cat():# This is constructor for pythondef __init__(self, name, age):self.name = nameself.age = age# Teaching each cat how to meowdef 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
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
The convention is for classes to begin with a capital letter in Python.
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: