OOPs In Python
Objects
- You create
objectsbased on theclasses. - When you write a
class, you defined the general behaviour that a whole category of objects can have.
Instantiation
- Making an
objectfrom acallis calledinstantiation, and you work withinstancesof a class.
NOTE
- You can also
extendthe functionality of existing classes. - You can also store your classes in module and import classes written by other programmers in to your own program files.
- You can model almost anything using classes.
Creating the DOG class
dog.py
class Dog:
"""A simple example to model a dog."""
def __init__(self,name,age):
""" Initialize name and age attributes."""
self.name = name
self.age = age
def sit(self):
""" Simulating a dog sitting."""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""Simulating a dog is rolling over."""
print(f"{self.name} rolled over!")
NOTE
- Class Name must start with a capital letter. (It should be capitalized).
By convention, capitalized names refer to classes in python.
The
__init__() method, is aspecial method that python run automatically, whenever we create a newinstance.We define the
__init__()method to have three parameters:self,nameandage. As per this example.The
selfparameter is required in themethoddefinition, and it must comefirst, before the other parameters.It must be included in the definition because, when python calls this method later (to create an
instanceofDog, in this example), the method call willautomaticallypass theselfargument.Every method call associated with an
instanceautomatically passesself, which is reference to theinstanceitself.
self <--> instance itself
it gives the individual instance access to the
attributesandmethodsin the class.What is
attributes?When we make an instance of "Dog", python will call the
__init__()method from theDogclass.