Python3 tutorial - 9 (Classes and Objects)

Welcome to CCP
Lets get started !

So, we have finally completed data structures and are ready to move on to some Complex terms,

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.


With help of classes, we can create our own custom data types,

excited to make one ?


see this:

I'll be using PyCharm, A handsome python text editor,


Here, Fruit class is empty and that's why we used the pass keyword to tell that the body is empty,

Seems pretty boring huh ?

lets fluff it with properties,

Note: properties contain the definitions and information for a class/blueprint

like this:


Here, we referenced the properties of apple and banana from the Dot Notation
notice the dot referencing, when we will try to print it, it will give:



I hope you understood,

Now,
suppose if you wanted to cut the Fruit object into half,
How would you do it ?
Make a function !

but as the function will belong to the class, we will call it Method

So, lets declare a method to slice or cut the Fruit object into half,
like this:


You can see here that we are calling the self attribute of the object,

self attribute is the first parameter of any method of any class but is not called as an argument when that method is called like we can see this in line 15 and line 6

self refers to the object itself and self.volume refers to volume of fruit1 object,
if their was fruit2 or fruit3, and self.volume was called, then it would've given the volume of each them,
and similarly other properties act:


Hope this is understood,

Lets move to the __init__() method of any class,

This is a special method, if it is present in any class, it runs automatically whenever a new object is generated of that class

and it saves a lot of time initializing the objects of class,
like this:


Here,
n, c and v are parameters to recieve name, color and volume and these are passed as arguments in Fruit() (constructor of the class)

So guys, this was the init method which saves programmers a lot of time,
hope you understood it,

See you later for more on printing objects !


Comments