Python OOPS
A class is a blue print from which specific objects are created.Classes provide a means of bundling data and functionality together.
Objects
An Object is an instance of a Class.An object consists of:
State:
It is represented by the attributes of an object. It also reflects the properties of an object.Behavior:
It is represented by the methods of an object. It also reflects the response of an object to other objects.Identity:
It gives a unique name to an object and enables one object to interact with other objects.
Example
class Dog: # A simple class # attribute attr1 = "mammal" attr2 = "dog" # A sample method def fun(self): print("I'm a", self.attr1) print( "I'm a", self.attr2) # Object instantiation Rodger = Dog() # Accessing class attributes # and method through objects print(Rodger.attr1) Rodger.fun() Output mammal I'm a mammal I'm a dog
Inheritance
A class can inherit attributes and behaviour methods from another class,called the superclass.A class which inherits from a superclass is called subclass or child class.
Example
class Animal: # attribute and method of the parent class name = "" def eat(self): print("I can eat") # inherit from Animal class Dog( Animal): # new method in subclass def display(self): # access name attribute of superclass using self print("My name is ", self.name) # create an object of the subclass labrador = Dog() # access superclass attribute and method labrador.name = "Rohu" labrador.eat() # call subclass method labrador.display() Output I can eat My name is Rohu
Encapsulation
Binding the data and code together as a single unit is called encapsulation.Securing data by hiding the implementation details to user.
Abstraction
Hides the implementation details and only provides the functionality to the users.We can achieve abstraction using abstract classes and interfaces.