DataScience - OOPS Part-1
'OOPS' stands for Object Oriented Programming System
Firstly, comes classes.
Classes are blueprint or skeleton or overall definition of OOPs things.
Eg. If I say there is a car, and ask you to sit inside. Then you will ask which one? Because there are many cars so u're confused.
You've probably understood meaning of car, it has 4 wheels, engine, brake, steering, etc. But which one? That you know only when I say u its color, model name, company name, etc.
So basically, 'car' is a skeleton or blueprint over here. So, u know its basic properties (4 wheels, steering, gear, brakes, etc). But u dont know the specific properties (color, model name, company, etc)
In short,
Class is a classification of real world entity.
Code:
a = 1
print(type(a))
o/p:
<class 'int'>
here, we get class integer as output, not the number.
Code:
print(type("PWSKILLS"))
o/p:
<class 'str'>
Similarly, we get class string here, but not the value.
Class is a blueprint of real world entity but not a specification of real world entity.
Object:
It is a real world entity/real world instance.
Code:
a = 1
Here, a is object or instance or variable of the integer class.
Creating a class:
use the 'class' keyword, which is a reserved keyword in Python Language.
Code:
class test :
o/p:
Cell In[4], line 1
class test :
^
SyntaxError: incomplete input
Error in output, bcoz there is nothing inside class which is not allowed.
So we put 'pass' to create blank class.
Code:
class test : pass
Why OOPs?
Because it makes the code reusable, structured and easy to use.
You can put variables, functions, modules inside class.
Creating object of class:
Code:
a = test()
type(a)
o/p:
__main__.test
its type is 'test'
Suppose we create a class with a method inside it:
class karanskills: def welcome_msg(): print("Welcome to class")
and we create variable 'rohan' of that class:
rohan = karanskills()
then we check type of it:
print(type(rohan))
o/p:
<class '__main__.karanskills'>
here, 'rohan' belongs to the type of class : karanskills
Now we try to call welcome_msg() method from object:
rohan.welcome_msg()
o/p:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[4], line 1
----> 1 rohan.welcome_msg()
TypeError: karanskills.welcome_msg() takes 0 positional arguments but 1 was given
Error is shown; It says 1 argument assgined but we haven't assgined any. then why did this happen?
Whichever method you define inside the class, you need to bind it / point it to the class so class can understand that it is own method of class.
For that u write word 'self'.
so, whenever you write a function inside a class, firstly, write 'self' with the function.
New Code:
class karanskills: def welcome_msg(self): print("Welcome to class")
rohan = karanskills()
rohan.welcome_msg()
o/p:
Welcome to class
Same with another object:
gaurav = karanskills()
gaurav.welcome_msg()
o/p:
Welcome to class