Overview
This article will explain the basics and how to use Object Oriented Programming when using classes in the Python programming language.
Materials
Python
IDE
What is Object Oriented Programming?
Object oriented programming fully utilizes the concept of objects. In any programming language, an object is a variable that holds data. For example, the String variable below is an object:
text = "hello"
The object "text" holds the string data "hello" if printed.
Another word or synonym for object creation is the word instantiation. Data is used to create or instantiate an object. Once again, the concept and the definition of objects in programming, is more specific when referred in the context of Object-Oriented Programming.
In Object-Oriented Programming, classes are an organized layout of code that is used to create objects in order to access and print object data or their attributes or methods more efficiently and securely.
How to make a Class
To create a class is created by doing the following:
class Name_Of_The_Class:
pass
To make a class, first write the word “class” then make a name for the class. The class’s name must be capitalized. Afterwards end it with a colin or “:”
Then press enter and a tab and begin writing within the class block. Above shows the simplest class, where only the keyword pass is within the class. It’s still a functionable class but since it only includes “pass” it won’t perform any significant changes.
Using Methods to Print Attributes from a Class
An attribute (1) is accessing a variable’s data from within a class. A method must be declared to print the class’s variable data, and that can be done by using the class name, then a dot, then the name of the attribute or variable within the class.
class Name_Of_The_Class:
first_variable = 1 # A class variable and an attribute
second_variable = 2
# How to print Attributes
print(Name_Of_The_Class.first_variable)
print(Name_Of_The_Class.second_variable)
Using Methods to Print Function Data from a Class
A method is returning data from a function that is within a class. To print a method, first write the name of the class, followed by a dot, and then the function name with the parenthesis:
class Name_Of_The_Class:
def function():
function_variable1 = 3
return function_variable1
# Printing a Class Function by using Method
print(Name_Of_The_Class.function())
A method in Python outside of OOP usually also follows the same syntax, that a variable is first needed, then a dot, then a built-in method to print some data.
Constructors
A constructor is a special function that is used to create new objects and uses a placeholder parameter to access other variables (2). The placeholder parameter is usually called “self”, but it can have a different name. Below is the format of a constructor:
def __init__(self, variable1, variable2............last_variable):
self.variable1 = "hello"
self.variable2 = "there"
Printing Variables from a Constructor
Below shows an example to print variables from a constructor, however, this way is not ideal as it does not use the self-parameter correctly:
class Shapes:
def __init__(self, shape1, shape2):
self.shape1 = shape1
self.shape2 = shape2
the_shapes = Shapes("Triangle", "Square")
print(the_shapes.shape1)
print(the_shapes.shape2)
How to use Self in a Constructor
Below shows how to use self in a constructor (3):
class One:
def __init__(self, variable1):
self.variable1 = variable1 # An instance attribute
def print_the_variable(self):
return self.variable1
the_instance_variable = One("hi").print_the_variable()
print(the_instance_variable)
When working with classes, the word instance will also be used quite often. An instance is a variable that is created that prints a class’s values from the constructor.
Once again, self is the default name for the parameter to access other variables, it can have another name. Below shows the same example as above where the self-parameters have different names:
class One:
def __init__(insert_parameter_name, variable1):
insert_parameter_name.variable1 = variable1
def print_the_variable(write_another_parameter_name):
return write_another_parameter_name.variable1
print( One("hi").print_the_variable() )
Public vs Private Variables
Any object that has two underscores before its name as shown below, is considered to be private and not public. Private data cannot be printed through class methods. Constructors are an example of private data too.
# Public
self.variable1 =
# Private
self.__variable1 =
Below shows an example of a class that has a private variable, and when trying to print the private variable directly without using the function, it will cause an error:
class example_class:
def __init__(self, variable1):
self.__variable1 = variable1
def function(self):
return self.__variable1
access_the_class = example_class("Hello")
print(access_the_class.function()) #This line of code will print the private variable
print(access_the_class.__variable1) #This line of code will NOT print the private variable
How Subclasses Can Overwrite Variables
There can be a scenario where the variable data in a superclass can be overwritten by its subclasses if the declared variables within the superclass and subclasses share the same variable names, and this should be avoided in some scenarios to not cause any problems. Below shows the superclass “One” has a variable named “variable1” and so does its subclass “Two”. Subclass “Two” overwrites One’s data for variable1. When a subclass changes the superclass’ data, this is called polymorphism.
class One:
variable1 = 2
class Two(One):
variable1 = 3
retrieve_data = Two()
print(One.variable1)
print(Two.variable1)
Super Classes and Sub Classes
The examples shown above had functions within classes. There is also a way to make another class inherit the properties of the original class. The original class is referred to as the super class and the class that inherits its properties is the sub class. Below shows the syntax for a super and sub class:
# The Super Class
class First_Class():
pass
# The Sub Class. In parenthesis, write the name of the superclass
# to inherit its attributes
class Second_Class(First_Class):
pass
A Further Look How to Use Inheritance
An example where a class has some properties that will be inherited by its subclass is shown below.
First, make a super class with a variable:
class Insert_Superclassname:
def __init__(self, variable1):
self.variable1 = variable1
Then, create another function called “def __str__(self):“ that returns the variable which contains a string (4)
class Insert_Superclassname:
def __init__(self, variable1):
self.variable1 = variable1
def __str__(self):
return self.variable1
An important note is the function “def __str__(self):” must be written as is to return the string.
Create a subclass that will inherit the superclass. In the subclass under the constructor, write the name of the subclass followed by a dot and then make a constructor:
class Insert_Superclassname:
def __init__(self, variable1):
self.variable1 = variable1
def __str__(self):
return self.variable1
class Insert_Subclassname(Insert_Superclassname):
def __init__(self, variable1):
Insert_Superclassname.__init__(self, variable1)
This is the proper methodology of how to inherit from the superclass. To print the content of the class, declare a variable outside the class.
class Insert_Superclassname:
def __init__(self, variable1):
self.variable1 = variable1
def __str__(self):
return self.variable1
class Insert_Subclassname(Insert_Superclassname):
def __init__(self, variable1):
Insert_Superclassname.__init__(self, variable1)
instance_var = Insert_Subclassname("Sample text")
print(instance_var)
Using super(). for Inheritance
Instead of writing out the actual name of the superclass for the subclass to read it, the keyword “super().” can be used rather than writing out the superclass name and the word self instead (5).
class Insert_Superclassname:
def __init__(self, variable1):
self.variable1 = variable1
def __str__(self):
return self.variable1
class Insert_Subclassname(Insert_Superclassname):
def __init__(self, variable1):
super().__init__(variable1)
superclass_instance_var = Insert_Superclassname("Sample text")
print(superclass_instance_var)
subclass_instance_var = Insert_Subclassname("More sample text")
print(subclass_instance_var)
Notice the constructor in the subclass includes the self and the same variable as the superclass. The next line shows the “super().” line that includes the variables that are already declared. The “super().” line inherits the variables from the superclass where if it is further overridden by the subclass, the variable values in the superclass and subclass would be different. An error would not occur because of “super().”.
Definitions
Object-Oriented Programming - Is the use of objects with classes
Object - A variable that holds data
Classes - Used to create objects, and are an efficient way to access attributes through methods
Class Variables - A variable declared in the class and outside any of the class functions or constructor is called a class variable.
Instantiate - A variable that is created to make an object. Usually, most objects are declared or instantiated in OOP outside the class to retrieve the content from the class by using methods.
Methods - A dot command that uses a “.“ to access class variables, instance variables or function variables within a class
Attributes - Qualities or variables that are defined in the class function or constructor parameters
Instances - A variable that is declared within the class’s function or constructor
Encapsulation - Private data that has less restrictions to be accessed through class methods
Superclass - A class that is declared to hold objects
Subclass - A class when created, can be written to inherit the properties of another class or the superclass.
Polymorphism - When a subclass overwrites data received from the superclass
Sources
https://docs.python.org/3/tutorial/classes.html (1)
https://www.geeksforgeeks.org/constructors-in-python/# (2)
https://www.w3schools.com/python/gloss_python_self.asp (3)