Advanced
title: Python Advanced description: Learn Advanced Python concepts like classes and objects, formatted strings, handling errors and variable scopes. keywords: [python advanced, classes and objects, formatted strings, handling errors, variable scopes] author: Juma Shafara date: "2023-11" date-modified: "2024-07-23"

In this notebook, we will explore some fundamental concepts in Python that are essential for writing clean, efficient, and maintainable code. These concepts include:
- Classes and Objects
- Formatted Strings
- Handling Errors
- Variable Scopes
Classes and Objects
In Python, everything is an object. A class helps us create objects.
Creating a Class
Instantiating a class
Now we can ceate an object from the class by instantiating it.
To instantiate a class, add round brackets to the class name.
After instantiating a class, we can now access the object's properties.
Class Attributes
A class can have attributes. Forexample the Person Class can have attributes like the name, height and feet
Note!
For now, focus on the syntax. Later we will explain the __init__() function and the self parameter.
Now that our class is ready, we can now instantiate it and provide values to it's attributes.
This process can also be called "creating an instance of a class".
An instance is simply the object created from a class
In this example, person_obj1 is a unique instance of the person class.
After that, we can now access the properties of the instance (object)
The self parameter allows us to access the attributes and methods of a class
The __init__() function allows us to provide values for the attributes of a class
Instances are unique
Let's say you have 500 people and you need to manage their data.
It is inefficient to create a variable for each of them, instead, you can create unique instances of a class.
In this example, the student1 and student2 instances are different from each other
class Student:
def __init__(self, id_number, name, age):
self.id_number = id_number
self.name = name
self.age = age
student1 = Student(5243, "Mary Doe", 18)
student2 = Student(3221, "John Doe", 18)
print("Student 1 ID:", student1.id_number)
print("Student 1 Name:", student1.name)
print("Student 1 Age:", student1.age)
print("---------------------")
print("Student 2 ID:", student2.id_number)
print("Student 2 Name:", student2.name)
print("Student 2 Age:", student2.age)
Methods
Methods are functions that can access the class attributes.
These methods should be defined (created) inside the class
As you may notice, we used the self parameter to access the feet attribute
You can also pass an argument to a method.
class Student:
def __init__(self, id_number, name, age):
self.id_number = id_number
self.name = name
self.age = age
def greet_student(self, greetings):
print("Hello" + self.name + ", " + greetings)
student1 = Student(43221, "Agaba Calvin", 18)
# the string below will be passed as
# the value of the greetings parameter
student1.greet_student("Welcome to this Python Tutorial!")
Python Inheritance
Inheritance is a feature that allows us to create a class that inherits the attributes or properties and methods of another class
Example
The Animal class below can be used to tell that an animal can eat
Let's say we need to create another class called Dog.
Since a dog is also an animal, it's more efficient to have access to all the properties and methods of the Animal class than to create another
This example creates a class named Dog and inherits from the Animal class
Note!
As you may notice, to inherit from a parent, we simply pass the name of that class as a parameter of the child class.
Now we can use the properties and methods of both the Animal and the Dog classes using just one instance
The super() and __init__ functions found in the Dog class allow us to inherit the properties and methods of the Animal class.
Parent and Child Class
The parent class is the class from whick the other class inherits from.
The child class is the the class that inherits from another class
In our example above, the Animal is the parent class while the Dog class is the child class
Formatted Strings
In Python, we can format a string by adding substring/s within it.
The format() function allows us to format strings.
Placeholders {}
Placeholders help us control which part of the string should be formated.
They are defined using curly braces {}.
In this example, we will concatenate (add) a substring to where the curly braces are placed
Multiple placeholders
If you want to format multiple parts of a string, use multiple placeholders.
Using Indexes
We can use index numbers to specify exactly where the values should be placed.
The index numbers should be inside the curly braces: {index_numbers}
Note!
0 represents the first value, 1 represents the second value and so on.
Using Named Indexes
We can also use named indexes to specify exactly where the values should be placed.
The arguments of the format() function should be in key/value pairs ie key=value.
The key/value pairs should be separated by commas.
Literal String Interpolation
Literal string interpolation allows you to use expression inside your strings.
Simply add f before you opening quote, then surround your expressions with curly braces {}.
Here's another example
Errors in Python
When coding in Python, you will encounter errors.
When errors occur, the program crashes or stops executing.
Fortunately, errors can be handled in Python
The try...except statment
The try...except statement is used to handle exceptions(errors)
The try statement takes a block of code to test for errors
The except statement handles the exceptions.
Note!
Even when the exception was thrown, the codes after the try...except were still executed
The else statement
The else statement is executed if there are no exceptions thrown.
The finally statement
The finally statement is executed whether or not an exception is thrown.
Throw Exceptions
We can intentionally throw and exception to stop the execution of a program.
The raise keyword throws an excrption.
Kinds of Exceptions
In Python, there are different kinds of exceptions and we can handle them individually with the try...except statement.
One of the most common kind of exceptions is the NameError. This is thrown when you use a variable that is not defined
Variable Scope
Python Variable Scopes
The accessibility of variable depends on its scope. In Python, there are two variable scopes:
- Global Scope
- Local Scope
Global Scope
A variable that is defined (created) outside a function has a global scope
A global variable can be accessed anywhere in a program
Local Scope
A variable that is defined (created) inside a function has a local scope. A local scope variable can only be accessed and used inside the function.
The global Keyword
We can force a local variable to be a global variable by using the global keyword.
Exercise
Develop a simple calculator to accept two floating point numbers from the keyboard. Then display a menu to the user and let him/her select a mathematical operation to be performed on those two numbers. Then display the answer. A sample run of you program should be similar to the following: