Python Chapter 4 object oriented programming
Python Chapter 4 object oriented programming
Hello everyone!
In this chapter, we are going to learn object-oriented programming. Let me
tell you one thing from this chapter we are turning towards the intermediate
level. So read it carefully.
So let's get started........
Course content:
- Classes
- The self
- Methods
- The 'init'
- Polymorphism
- Data encapsulation/abstraction
- Inheritance
What is object-oriented programming?
- We have designed our program around functions in all the programs we wrote, i.e., blocks of statements that manipulate data. This is called the procedure-oriented way of programming.
- There is another way of organizing a program: combining data and functionality and wrapping it inside something called an object.
- This is called the object-oriented programming paradigm.
- One can use procedural programming most of the time, but when writing large programs or having a problem that is better suited to this method, you can use object-oriented programming techniques.
- Classes and objects are the two main aspects of object-oriented programming.
- A class creates a new type where objects are instances of the class.
- An analogy is that you can have variables of type int, which translates to saying that variables that store integers are variables that are instances (objects) of the int class.
- Fields are of two types - they can belong to each instance/object of the class or belong to the class itself. They are called instance variables and class variables, respectively.
- A class is created using the class keyword. The fields and methods of the class are listed in an indented block.
Classes
- We create a new class using a class statement and the name of the class. This is followed by an indented block of statements that form the body of the class. In some cases, we have an empty block which is indicated using the pass statement.
- We create an object/instance of a class using the name of the class followed by a pair of parentheses.
- For our verification, we can confirm the type of the variable by simply printing it.
- It tells us that we have an instance of the "Person" class in the main module.
- Notice that the address of the computer memory where your object is stored is also printed.
class Person:
pass
p=Person()
print(p)
Output=__main__.Person object at 0x000002986739FA60>
The self
- Class methods have only one specific difference from ordinary functions - they must have a different first name that must be added to the beginning of the parameter list. Still, you do not give a value for this parameter when you call the method. Python will provide it.
- This particular variable refers to the object itself, and by convention, it is given the name self.
- Although you can give any name for this parameter, you strongly recommend that you use the name self - any other name is definitely frowned upon.
- There are many advantages to using a familiar name - any reader of your program will immediately recognize it, and even specialized IDEs (Integrated Development Environments) can help you if you use self.
- How Python gives the value for self and why we don't need to value it.
- Let us have a class called List and an instance of this class called shop list.
- When we call a method of this object as shop list. Append ('milk'), this is automatically converted by Python into List. Append (shop list, 'milk') - this is all the particular self is about.
- This also means that if you have a method that takes no arguments, then you still have to have one argument - the self.
- The self in Python is equivalent to this pointer in C++ and this reference in Java and C#.
Methods
- Class/objects can have methods just like functions except that we have an extra self variable.
- We see the self in action in the given an example.
- Notice that the say_hi method takes no parameters but still has the self in the function definition.
class Person:
def say_hi(self):
print("Hello how are you?")
p=Person()
p.say_hi()
Output=Hello how are you?
You can also write in this way
Person().say_hi()
Output=Hello how are you?
The init
- Many method names have special significance in python classes
- The init method is run as soon as an object of a class is instantiated.
- The method is helpful to do any initialization you want to do with your object.
- Notice the double underscores both at the beginning and at the end of the name.
- We do not explicitly call the init method but pass the arguments in the parentheses following the class name when creating a new class instance.
class Person:
def __init__(self,fname):
self.name=fname
q=Person('Himanshu')
p=Person('Dharmesh')
class Person:
def __init__(self,fname):
self.name=fname
def say_hi(self):
print('Hello,my name is',self.name)
p=Person("Dharmesh")
p.say_hi()
Output=Hello,my name is Dharmesh
q=Person('Himanshu')
q.say_hi()
Output=Hello,my name is Himanshu
Polymorphism
- Polymorphism is achieved through method overloading. Method overloading means several methods present in a class have the same name but different types/number of parameters. Like other languages, Python does not support method overloading by default. But there are different ways to achieve Polymorphism in Python.
- Polymorphism is an ability (in OOP) to use a standard interface for multiple forms (data types). Suppose we need to color a shape; there are multiple shape options (rectangle, square, circle). However, we could use the same method to color any shape.
- This concept is called Polymorphism.
- In the given program, we will define two classes Parrot and Penguin. Each of them has a standard method fly(). However, their functions are different.
class Parrot:
def fly(self):
print("Parrot can fly")
class Penguin:
def fly(self):
print("Penguin can't fly")
def flying_test(bird):
bird.fly()
blu = Parrot()
peggy = Penguin()
flying_test(blu)
Output=Parrot can fly
flying_test(peggy)
Output=Penguin can't fly
Data encapsulation/abstraction
- Abstraction is an essential aspect of object-oriented programming.
- In Python, we can perform data hiding by adding the double underscore () as a prefix to the attribute which is to be hidden. After this, the attribute will not be visible outside of the class through the object.
- Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct modification, which is called encapsulation.
- We defined a class Computer. We use_init the__() method to store the maximum selling price of the computer.
- We try to modify the price. However, we can't change it because Python treats the __maxprice as personal attributes.
- We used a setter function set a price() to change the value, taking price as a parameter.
class Computer:
def __init__(self):
self.__maxprice=900
self.actual_price=500
def sell(self):
print("Selling price: ",self.__maxprice)
print("Actual price: ",self.actual_price)
def setMaxPrice(self,price):
self.__maxprice=price
c=Computer()
c.__maxprice()
AttributeError: 'Computer' object has no attribute '__maxprice'
c.actual_price
Output=500
c.sell()
Output=Selling price: 900
Actual price: 500
c.__maxprice=1000
c.actual_price=600
c.sell()
Output=Selling price: 900
Actual price: 600
c.setMaxPrice(1000)
c.sell()
Output=Selling price: 1000
Actual price: 600
Inheritance
- One of the major benefits of object-oriented programming is the reuse of code and one of the ways this is achieved is through the inheritance mechanism.
- Inheritance can be best imagined as implementing a type and subtype relationship between classes.
- Suppose you want to write a program which has to keep track of the teachers and students in a college.
- They have some common characteristics such as name, age, and address. They also have specific characteristics such as salary, courses, and leaves for teachers and, marks and fees for students.
- You can create two independent classes for each type and process them but adding a new common characteristic would mean adding to both of these independent classes. This quickly becomes unwieldy.
- A better way would be to create a common class called School Member and then have the teacher and student classes inherit from this class i.e. they will become sub-types of this type (class) and then we can add specific characteristics to these sub-types.
- There are many advantages to this approach.
- If we add/change any functionality in School Member, this is automatically reflected in the subtypes as well.
- Also, observe that we reuse the parent class code, and we do not need to repeat it in the different classes as we would have had to if we had used independent classes.
- The School Member class in this situation is known as the base class or the superclass.
- The Teacher and Student classes are called the derived classes or subclasses.
class SchoolMember:
def __init__(self,name,age):
self.name=name
self.age=age
print("Intialized SchoolMember",self.name)
def tell(self):
print("Name: {} Age: {}".format(self.name, self.age))
class Teacher(SchoolMember):
def __init__(self,name,age,salary):
SchoolMember.__init__(self,name,age)
self.salary=salary
print("Intialized Teacher",self.name)
def tell(self):
SchoolMember.tell(self)
print("Salary",self.salary)
class Student(SchoolMember):
def __init__(self,name,age,marks):
SchoolMember.__init__(self,name,age)
self.marks=marks
print("Intialized Student",self.name)
def tell(self):
SchoolMember.tell(self)
print("Marks: ",self.marks)
t1=Teacher('Mr.Himanshu',33,250000)
Output=Intialized SchoolMember Mr.Himanshu
Intialized Teacher Mr.Himanshu
t1.tell()
Output=Name: Mr.Himanshu Age: 33
Salary 250000
Perform the student class operations
I hope that you have understood this topic in the next chapter we will learn
about dates and times in Python.
So stay tuned!
Join the conversation