Python Classes – Objects – Modules & Functions
Let us see Python Classes, Objects, Modules and Functions
We have the below topics covered as part of Python learning course.
Watch on YouTube: https://youtu.be/YUz1XDbJDlI
Classes & Objects
Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a “blueprint” for creating objects.
Creating Class
class MyClass: empid = 1001 empname = "John"
Creating object for the class
obj1 = MyClass() print(obj1.empid) print(obj1.empname)
The __init__() Function
This is kind of Python’s standard initialize method which is invoked during object creation of the class. consider you want to pre-initialize the properties of the class ahead of object creation, then you need to use this method.
class Student: def __init__(self, sid, name, age): self.sid = sid self.name = name self.age = age # ------------------------------------------- student1 = Student(100,"Bob", 22) print(student1.sid) print(student1.name) print(student1.age)
In the above class we have “init” method which gets initialized along with the constructor while creating an object and we have self as our first parameter, which is used for identifying the current/own object.
Note: The \__init\__() function is called automatically every time the class is being used to create a new object.
The self Parameter
The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class and It doesn’t need to be named like “self”.
We can call it whatever we want, but it should be the first parameter of any function in the class, see below example..
class Car: def __init__(myownobjectref, carid, carmake): myownobjectref.carid = carid myownobjectref.carmake = carmake
Note: In the above example we have used myownobjectref as first parameter and it refers the current object of Car class.
Modify object properties
class Student: def __init__(self, sid, name, age): self.sid = sid self.name = name # ------------------------------------------- student1 = Student(100,"Bob") student1.sid = 101
Delete object properties
class Student: def __init__(self, sid, name, age): self.sid = sid self.name = name # ------------------------------------------- student1 = Student(100,"Bob") del student1.sid
Delete object
class Student: def __init__(self, sid, name, age): self.sid = sid self.name = name # ------------------------------------------- student1 = Student(100,"Bob") del student1
Modules
Python Modules
Python modules are .py files that consist of Python code. Any Python file can be referenced as a module.
Some modules are available through the Python Standard Library and are therefore installed with your Python installation. Others can be installed with Python’s package manager pip. Additionally, you can create your own Python modules since modules are comprised of Python .py files.
Writing and Importing Modules
Writing Modules
Writing a module is just like writing any other Python file. Modules can contain definitions of functions, classes, and variables that can then be utilized in other Python programs.
From our Python 3 local programming environment or server-based programming environment, let’s start by creating a file hello.py that we’ll later import into another file.
To begin, we’ll create a function that prints Hello, World!:
# math_operations.py (Located under my-own-modules directory)
# Maths Operation
def add(a, b):
print(a + b)
If we run the program on the command line with python math_operations.py nothing will happen since we have not invoked the functions add.
Importing Modules
Let’s create a second file called main_program.py so that we can import the module we just created, and then call the function.
main_program.py
# Import math_operations module - which is nothing but the math_operations.py file
import math_operations
# Call function
math_operation.add(1, 2)
Because we are importing a module, we need to call the function by referencing the module name in DOT " . " notation.
We could instead import the module as from hello import world and call the function directly as world(). You can learn more about this method by reading how to using from … import when importing modules.
Functions
Python Functions
Python functions are written inside .py files which performs the instruction or action written in Python. each method/function performs set of instruction or operations we wanted to perform. like adding two numbers, checking if the user is admin or not etc.,
Creating Function
In order to create python functions/methods you need to use def key word prefixed. lets see the below example.
# functions.py
# def -> key word tells us this is a method.
# display_app_name(): this is our method name with no parameters, because with in the brackets we have not passes any variable.
def display_app_name():
print("My App Name")
Calling Function
Calling a medhod in Python is easy, just need to use the method name with the brackets. (If method has any parameters, we need to just pass it inside the brackets.)
# calling the function
display_app_name()
Returning data from Function
# functions.py
def get_current_username(user):
return user["name"]
userobj = {
"name": "John",
"id": 100}
print(get_current_username(userobj))
Calling function inside another function.
# functions.py
def is_admin(user_param):
return user_param["admin"]
def append_usertype(old_user_id, user_type):
return f"{old_user_id}_{user_type}"
def regenerate_userid(user_param):
new_userid = user_param["id"]
if is_admin(user_param):
new_userid = append_usertype(new_userid,"ADM")
else:
new_userid = append_usertype(new_userid,"USR")
user_param["id"] = new_userid
return user_param
#-----------------------------------------
user = {
"name": "John",
"id": 100,
"admin": False
}
print(user)
print(regenerate_userid(user))
