29
loading...
This website collects cookies to deliver better user experience
Class: To define a Class, we use the class
keyword and initialize it with the name of the class. Note: The name is in Camel-case.
Constructor: init
is a dunder method, a special kind of function. We will discuss dunder methods later but what it basically does is help us construct any attributes of the Class hence called a constructor.
Attributes: So what exactly are attributes? It’s a fancy term used for variables inside the Class.
Method: Method is another fancy term used for Functions inside a Class. It’s generally a good idea to know the terms as they are widely used but none of the basic idea changes just cause they are inside a Class.
self: When I got first introduced to object-oriented programming I had a tough time understanding what self does. I will be explaining in detail in the next blogpost but for now, accept it as something that allows the object; we will create to access both the attribute and the method inside a class. It will become a bit more clear when we understand Objects. 👇🏼
mammal.py
we import the Animal Class. It’s not necessary but recommended as separating your code into two different files makes debugging easier. Once imported we create the object, let’s dive into the code and how it works internally.dog1
and dog2
using the Animal class, just by assigning two different variables to store the Object into. I have used keyword arguments to declare the values but can be done using positional arguments too.What exactly happens under the hood is when I declare the Animal class and pass on the name & the breed it constructs the Object based on the blueprint of the Animal Class which is defined by the init
method. Here the self
word helps in connecting the arguments declared while creating the Object in main.py
with the attributes inside the Class Animal in mammal.py
.
breathe()
method on each of the variables inside the main.py
would call the Function inside the Animal Class and do whatever is defined inside the Function. Here’s it to print 'Inhale - Exhale'
.What exactly happens under the hood is when the method is called on the Object created, it passes the Object (dog1, dog2, or dinosaur1) on the self
parameter and then calls the Function to do the action defined inside the Function. This means that dog1.breathe()
translates to Animal.breathe(dog1)
.
tail
for the Object dog2
as False
. One of the blessings of using object-oriented programming or OOP is that you can change and create variables on the go.dog2.tail = False
is an example of changing the value. dinosaur1.horn = True
is an example of adding a new attribute to the Object.