Object-oriented programming (OOP)
There are generally two approached to organise code:
  1. 1.
    Procedural programming: using a function that accomplishes a task or returns a result.
  2. 2.
    Object-oriented programming (OOP): using properties and behaviours.

Object-oriented programming (OOP)

It uses objects as a way to structure the code. You can define these objects in terms of properties and behaviours. It is perfectly fine to follow the procedural way of programming in Python, but it may not be wise because Python was designed to be in object-oriented programming language and can offer so much more.
OOP has more feature, including design pattern. Design patterns require object-oriented programming. Therefore, if you want to use design pattern in your code, then you have not a choice but to use OOP.

What Makes Python OOP?

The answer is very straight forward. Python supports:
  • Class
  • Attribute
  • Method
  • Constructor: In Python, the init() method is called the constructor and is always called when an object is created.
  • Inheritance
These are also building blocks of design patterns.

What is an Object?

  • An entity or 'thing' in your Python code or programme, often a noun.
  • Example of an object could be a person (single person).

Properties:

  • Name
  • Age
  • Gender
  • Address etc......

Behaviours:

  • Shopping
  • Swimming
  • Walking
  • Talking etc........
Common example of classes

How are Objects Created?

You can create Objects in Python using Classes. You can create many and unique objects from a class. The process to create an object from a class is known as instantiation.
An example of instantiation is the built-in types like int, str etc. Let's create a variable by assigning a value/string to it.
1
city_name = 'Krakow'
Copied!
The variable city_name with a value of Krakow. The variable city_name is a reference to an object. Krakow has object type str because the built-in class str was instantiated in order to create it.
You can create many objects from a single class, and you can instantiate the class to create as many as unique objects you want. They will all have the same type, but they can store different values for their individual properties.

Classes and Instances

This is focused on the basics of creating and instantiating simple classes. But why should we even use classes?
It allows to logically group data and functions that are easy to reuse and add complexity to it. When I say attributes and methods, I mean data and functions. A method is a function that is associated with a class.
Let's create a class and take the course as an example. You are students attending Introduction to DS with Python course. Each student has specific attributes and methods.
For example; each student has a name, email address and fee to pay as well as actions that you can perform. So it is nice to have a class as a blueprint to create each student so that you do not have to add new students manually from scratch.
Let's create student class by simply calling class keyword
1
class Students:
2
pass
Copied!
You will get an error if you leave the class empty. You can use pass keyword so the code runs successfully and you can add methods to it later.
The Student class is basically a blueprint for creating INSTANCES and each unique student that we create using our Student class will be an instance of that class.
1
student1 = Student()
2
student2 = Student()
Copied!
These two instances are unique instances of the Student class and occupy different locations. You can check their memory address as well.
Code
Output
1
print(student1)
2
print(student2)
3
​
4
# or
5
​
6
print(hex(id(student1)))
7
print(hex(id(student2)))
Copied!
1
#print(student1)
2
#print(student2)
3
<__main__.Student object at 0x7fd1b161d0b8>
4
<__main__.Student object at 0x7fd1b161d080>
5
​
6
#print(hex(id(student1)))
7
#print(hex(id(student2)))
8
0x7fd1b161d0b8
9
0x7fd1b161d080
Copied!

Instance Variables/Attributes

Instance variables contain data that is unique to each instance. You can manually create instance variables for each student similar to above.
1
student1.name = 'Pawel'
2
student1.surname = 'Pawlowski'
3
student1.email = '[email protected]'
4
student1.fee = 4000
5
​
6
# You can add second students
7
student2.name = 'Marta'
8
student2.surname = 'Pawlowska'
9
student2.email = '[email protected]'
10
student2.fee = 4400
Copied!
As you see, each instances have attributes that are unique to them. Let's print surname of student1 and student2.
Code
Output
1
print(student1.surname)
2
print(student2.surname)
Copied!
1
#print(student1.surname)
2
#print(student2.surname)
3
​
4
Pawlowski
5
Pawlowska
Copied!
This is a very tiring process to create for each student all the attributes manually. It is good to set all this information for each student automatically.
The more the codes, the more it is likely to make mistakes.
In order to create all the information automatically. You are going to use a special init method.
1
class Students:
2
3
def __init__(self, name, surname, fee, fee_status):
4
self.name = name
5
self.surname = surname
6
self.fee = fee
7
self.fee_status = fee_status
8
self.email = name + '.' + surname + '@gmail.com'
Copied!
When you create a method within a class, they receive the instance as the first argument automatically. It is customary that we call the instance self. You can call it whatever you like similar to args and kwargs.
After self, you can add the parameters (arguments) you want. In this case, student name, surname, fee. I know we had email as well, but we are creating an email from name and surname, so we can automate it.
Now, you can pass your values into the class when you are instantiating it.
Code
Output
1
student3 = Student('Zmnako', 'Awrahman', 0, 'Paid')
2
​
3
print(student3.name)
4
print(student3.surname)
5
print(student3.email)
6
print(student3.fee)
7
print(student3.fee_status)
Copied!
1
#print(student3.name)
2
#print(student3.surname)
3
#print(student3.email)
4
#print(student3.fee)
5
#print(student3.fee_status)
6
​
7
Zmnako
8
Awrahman
9
10
0
11
paid
Copied!
As you can see, the init method run automatically when you instantiated the class. student3 will be passed in as self and the attributes are set.
The parameters, such as name, surname, email and fee, are attributes of the Student class.

Instance Methods

Let's add some action that each student can perform. In order to get this ability, you have to add some methods to the class.
Let's say, you want to get the full name of a student and fee status. You can either do this outside of the class or inside the class.
Outside the class you can do it as follow:
1
print('{} {} {}'.format(student3.name,
2
student3.surname,
3
student3.fee_status))
Copied!
But it is recommended to create a method within your class that allows you to put this ability in one place and reuse it everywhere else that you need it.
The method within the class takes the instance (self) as first parameters. The instance is the only parameters that you need to get a student's full name. You can take the logic outside of the class as a return inside the method. You have to use self with each attribute inside the class instead of the instantiated object from the class student3.
1
class Student:
2
3
def __init__(self, name, surname, fee, fee_status):
4
self.name = name
5
self.surname = surname
6
self.fee = fee
7
self.fee_status = fee_status
8
self.email = name + '.' + surname + '@gmail.com'
9
10
def full_name(self):
11
return '{} {}'.format(self.name, self.surname)
Copied!
Now, you can use the method full_name with the Student class
1
student4 = Student('Marco', 'Lucas', 4000, 'unpaid')
2
​
3
# To get full name
4
student4.full_name()
5
​
6
# Output
7
'Marco Lucas'
Copied!
if we remove the parenthesis, you can see it prints method
1
student4.full_name
2
​
3
# Output
4
<bound method Student.full_name of <__main__.Student object at 0x7fd1b15a4668>>
Copied!
There is a very common mistake when creating a method is people forget to pass self parameter for the instance.

Class Variables

Class variables are variables that are shared among all instances of a class. While the instance variable can be unique for each instance, such as name, surname, fee etc., class variables should be the same for each instance. If you look at the class you created earlier
1
class Student:
2
3
def __init__(self, name, surname, fee, fee_status):
4
self.name = name
5
self.surname = surname
6
self.fee = fee
7
self.fee_status = fee_status
8
self.email = name + '.' + surname + '@gmail.com'
9
10
def full_name(self):
11
return '{} {}'.format(self.name, self.surname)
Copied!
Let's say that the course will give discounts to students who register early and pay the full fee at least a month before the course start date. This discount should be the same for all instances of the Student class. The discount is a good candidate for a class variable.
Let's hardcode the class variable to the class created earlier. You can create a method within the class to apply a 10% discount to early birds.
1
class Student:
2
3
def __init__(self, name, surname, fee, fee_status):
4
self.name = name
5
self.surname = surname
6
self.fee = fee
7
self.fee_status = fee_status
8
self.email = name + '.' + surname + '@gmail.com'
9
10
def full_name(self):
11
return '{} {}'.format(self.name, self.surname)
12
13
def apply_discount(self):
14
self.fee = int(self.fee * 0.90)
Copied!
Let's use the apply_discount method
1
student6 = Student('Piotr', 'Kyc', 4000, 'unpaid')
2
​
3
print(student6.fee)
4
# Apply discount
5
student6.apply_discount()
6
print(student6.fee)
7
​
8
# Output
9
4000
10
3600
Copied!
This is OK, but you cannot see what is the discount amount is and it is difficult to change the discount rate for each stage of recruitment. As I mentioned, this is a hardcoded way and it is not recommended.
The discount rate is fixed and hidden in the apply_discount. If you want to change it, you have to go within the class to change it. Going from the hardcoded version to a class variable is very easy. You just go above all methods and create a variable.
1
class Student:
2
​
3
discount_amount = 0.90
4
5
def __init__(self, name, surname, fee, fee_status):
6
self.name = name
7
self.surname = surname
8
self.fee = fee
9
self.fee_status = fee_status
10
self.email = name + '.' + surname + '@gmail.com'
11
12
def full_name(self):
13
return '{} {}'.format(self.name, self.surname)
14
15
def apply_discount(self):
16
self.fee = int(self.fee * discount_amount)
Copied!
Running this raises a NameError message
1
student6 = Student('Piotr', 'Kyc', 4000, 'unpaid')
2
​
3
print(student6.fee)
4
# Apply discount
5
student6.apply_discount()
6
print(student6.fee)
7
​
8
# Output
9
NameError Traceback (most recent call last)
10
<ipython-input-81-bc754d2afbf2> in <module>()
11
3 print(student6.fee)
12
4 # Apply discount
13
----> 5 student6.apply_discount()
14
6 print(student6.fee)
15
​
16
<ipython-input-80-a377950cc839> in apply_discount(self)
17
14
18
15 def apply_discount(self):
19
---> 16 self.fee = int(self.fee * discount_amount)
20
​
21
NameError: name 'discount_amount' is not defined
Copied!
This is because the method cannot access the discount amount. You can pass the discount amount either through the class itself or an instance of the class.

Solution 1:

Access the discount amount through the class itself by using Student.discount_amount.
1
class Student:
2
​
3
discount_amount = 0.90
4
5
def __init__(self, name, surname, fee, fee_status):
6
self.name = name
7
self.surname = surname
8
self.fee = fee
9
self.fee_status = fee_status
10
self.email = name + '.' + surname + '@gmail.com'
11
12
def full_name(self):
13
return '{} {}'.format(self.name, self.surname)
14
15
def apply_discount(self):
16
self.fee = int(self.fee * Student.discount_amount)
Copied!
Output:
1
student6 = Student('Piotr', 'Kyc', 4000, 'unpaid')
2
​
3
print(student6.fee)
4
# Apply discount
5
student6.apply_discount()
6
print(student6.fee)
7
​
8
# Output
9
4000
10
3600
Copied!

Solution 2:

Access through the instance by using self.
1
class Student:
2
'''
3
This is my class
4
'''
5
discount_amount = 0.10
6
7
def __init__(self, name, surname, fee, fee_status):
8
self.name = name
9
self.surname = surname
10
self.fee = fee
11
self.fee_status = fee_status
12
self.email = name + '.' + surname + '@gmail.com'
13
14
def full_name(self):
15
return '{} {}'.format(self.name, self.surname)
16
17
def apply_discount(self):
18
self.fee = int(self.fee * (1 - self.discount_amount))
Copied!
Output:
1
student6 = Student('Piotr', 'Kyc', 4000, 'unpaid')
2
​
3
print(student6.fee)
4
# Apply discount
5
student6.apply_discount()
6
print(student6.fee)
7
​
8
# Output
9
4000
10
3600
Copied!
You can access all the keys and values in a class by using __dict__.
1
student6.__dict__
2
​
3
# Output
4
{'email': '[email protected]',
5
'fee': 3600,
6
'fee_status': 'unpaid',
7
'name': 'Piotr',
8
'surname': 'Kyc'}
Copied!
As you can see, all arguments with their values are returned in a dictionary, but the discount amount is missing. But if you do the same thing for the class, you get a different result.
1
Student.__dict__
2
​
3
# Output
4
mappingproxy({'__dict__': <attribute '__dict__' of 'Student' objects>,
5
'__doc__': None,
6
'__init__': <function __main__.Student.__init__>,
7
'__module__': '__main__',
8
'__weakref__': <attribute '__weakref__' of 'Student' objects>,
9
'apply_discount': <function __main__.Student.apply_discount>,
10
'discount_amount': 0.1,
11
'full_name': <function __main__.Student.full_name>})
Copied!
The discount_amount is the class variable that your instances see and access it when you are instantiating Student class.

How to Change the Discount Amount?

You can change the discount amount by updating it.
Code
Output
1
student7 = Student('Piotr', 'Kyc', 4000, 'unpaid')
2
student8 = Student('Marco', 'Lucas', 4000, 'unpaid')
3
​
4
student7.discount_amount = 0.2
5
​
6
print(Student.discount_amount)
7
print(student7.discount_amount)
8
print(student8.discount_amount)
Copied!
1
#print(Student.discount_amount)
2
#print(student7.discount_amount)
3
#print(student8.discount_amount)
4
​
5
0.1
6
0.2
7
0.1
Copied!

Homework?

Can you add a Class Variable for the number of students enrolled? If the number of students reaches 10 registered students, Add the students to a waiting list.

You can read further details in this free Python Textbook on OOP (Object-Oriented Programming in Python Documentation)
Last modified 1yr ago