Advanced

Classes and Objects

In Python, everything is an object.A class helps us create objects.

Creating a Class

Use the class keyword to create a class

class Person:
    first_name = "Betty"
    last_name = "Kawala"
    age = 30

## 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.

person_obj1 = Person()

type(person_obj1)
__main__.Person
# print attributes
print(person_obj1.first_name)
print(person_obj1.last_name)
print(person_obj1.age)
Betty
Kawala
30

Class Attributes

A class can have attributes. Forexample the Person Class can have attributes like the name, height and feet

class Person:
    def __init__(self, name, height, feet):
        self.name = name
        self.height = height
        self.feet = feet
person_obj1 = Person(name='Betty Kawala', height=1.57, feet=4)

print('Name:', person_obj1.name)
print('Height:', person_obj1.height)
print('Feet:', person_obj1.feet)
Name: Betty Kawala
Height: 1.57
Feet: 4

Methods

Methods are functions that can access the class attributes. These methods should be defined (created) inside the class

class Person:
    def __init__(self, name, height, feet):
        self.name = name
        self.height = height
        self.feet = feet
        
    def jump(self):
        return "I'm jumping " + str(self.feet) + " Feet"
person_obj1 = Person(name='Juma', height=1.59, feet=5)

print(person_obj1.jump())
I'm jumping 5 Feet

As you may notice, we used self parameter to access the feet attribute.

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

class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print(f"{self.name} is eating.")

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

class Dog(Animal):
    def __init__(self, name, age, color):
        super().__init__(name, age)
        self.color = color

    def sound(self):
        print(self.name, "barks")

Now we can use the properties and methods of both the Animal and the Dog classes using just one instance

dog1 = Dog(name='Brian', age=8, color='White')
dog1.eat()
dog1.sound()
Brian is eating.
Brian barks

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

More Class and Inheritance Examples

Animal

class Animal:
    def __init__(self, name, sound):
        self.name = name 
        self.sound = sound

    def speak(self):
        print(self.name + ' is ' + self.sound + 'ing')

class Dog(Animal):
    def __init__(self, name, sound):
        super().__init__(name, sound)

    def walk(self):
        print( self.name + ' is ' + 'walking...')
        # return
    

class Snake(Animal):
    def __init__(self, name, sound):
        super().__init__(name, sound)

    def crawl(self):
        print(self.name + ' is ' + 'crawling..')

snake1 = Snake(name='Sensei', sound='Hiss')

snake1.speak()
Sensei is Hissing

Library

class Library:
    def __init__(self, name):
        self.name = name
        self.books = []    # list of books
        self.lent_books = [] # list of lent books

    # add book to the library
    def addBook(self, book):
        self.books.append(book) 

    # add many books to the library
    def addManyBooks(self, books):
        self.books.extend(books)

    # display books in the library
    def displayBooks(self):
        for book in self.books:
            print(book)

    # lend book to a person
    def lendBook(self, title, person):
        for book in self.books:
            if book.title == title:
                if book.title not in self.lent_books:
                    person.borrowed_books.append(book)
                    self.lent_books.append(book.title)
                    return
                else:
                    print(title + ' is not availabe')
                    return
        print('There no such book in the library') 

    def __str__(self):
        return str(self.name)
class Book:
    def __init__(self, title, author):
        self.title = title 
        self.author = author
        self.available = True

    def __str__(self):
        return str(self.title)
class Person:
    def __init__(self, name):
        self.name = name
        self.borrowed_books = [] # list of borrowed books

    # display all borrowed books
    def displayBooks(self):
        for book in self.borrowed_books:
            print(book)

    def __str__(self):
        return str(self.name)
# create our library
stat_library = Library(name='Stat-Lib')
# create our people
viola = Person(name='Viola')
shafara = Person(name='Shafara')
betty = Person(name='Betty')
# create our books
our_books = [
    Book(title='Song of Lawino', author="Okot p'Bitek"),
    Book(title='Da Vinci Code', author='Dan Brown'),
    Book(title='Harry Potter', author='JK Rowling')
] 

# add books to the library
stat_library.addManyBooks(books=our_books)
# display available books in the library
stat_library.displayBooks()
Song of Lawino
Da Vinci Code
Harry Potter
# lend out book 
stat_library.lendBook(title='Harry Potter', person=betty)
# lend out book
stat_library.lendBook(title='Song of Lawino', person=betty)
# display books borrowed by Betty
betty.displayBooks()
Harry Potter
Song of Lawino
# display all lent out books
stat_library.lent_books
['Harry Potter', 'Song of Lawino']
# try lending out an already lent book
stat_library.lendBook(title='Song of Lawino', person=viola)
Song of Lawino is not availabe
# lend out book
stat_library.lendBook(title='Da Vinci Code', person=viola)
# try lending out non existent book
stat_library.lendBook(title='Angels and Demons', person=shafara)
There no such book in the library

Formatted Strings

statement = '{} loves to code in {}'

formatted = statement.format('Juma', 'JavaScript')

print(formatted)
Juma loves to code in JavaScript
name = 'Juma'; language = 'JavaScript'

statement = f'{name} loves to code in {language}'

print(statement)
Juma loves to code in JavaScript
answer = f'The summation of 5 and 7 is {5 + 7}'

print(answer)
The summation of 5 and 7 is 12
# Using indexes

name = 'Juma'
language = 'javascript'

statement = f'{name} loves to code in {language}'

modified = statement.format(language='JavaScript', name='Juma')

print(modified)
Juma loves to code in javascript
name = 'Viola'
fruit = 'orange'
expression = 'so much'

# positional formating
statement = '{} loves my {}'.format(name, fruit)

print(statement)
Viola loves my orange
# indexing
statement = '{0} loves my {1}'.format(name, fruit)

print(statement)
Viola loves my orange

try…except

# try:
#     statements
# except:
#     statements
def dataideaArithmetic(x, y, operation):
    if operation == '+':
        return x + y
    elif operation == '-':
        return x - y
    elif operation == '/':
        return x / y 
    else:
        return x * y
print('''
    DATAIDEA Arithmects:
      
Instructions
-------------------------
Enter only two numbers and the operation as +, -, /, x
''')


# number1 = float(input('Enter first number: '))
# number2 = float(input('Enter second number: '))
# operator = input('Enter the operator: ')


try:
    answer = dataideaArithmetic(number1, number2, operator)
    print(f'{number1}{operator}{number2} = {answer}')
except:
    print('A problem occured while running the operation')
else:
    print('Your code has run successfully!')
finally:
    print('Code execution complete.')

try:
    # age = input('Enter your age: ')
    age = '32'
    age_integer = int(age)

    if age_integer >= 18:
        print('Your vote has been cast')
    else:
        print('You are not eligible to vote')
except ValueError:
    print('A problem occured while picking your age \n'
          'You did not enter a number')
else:
    print('Thanks for participating!')

    DATAIDEA Arithmects:
      
Instructions
-------------------------
Enter only two numbers and the operation as +, -, /, x

2.022.0 = 4.0
Your code has run successfully!
Code execution complete.
You are not eligible to vote
Thanks for participating!
# Creating your own errors

try: 
    # age = int(input('Enter your age: '))
    age = ''

    if age < 18:
        raise Exception('Not an adult')
except Exception as error:
    print('A problem occurred \n'
          f'Error: {error}')
A problem occurred 
Error: '<' not supported between instances of 'str' and 'int'

Variable Scope

# local scope
# a variable that is created/defined 
# inside a function has a local scope

# create a fucntion that greats people

# - All variable declared outside a function global

name = 'Voila'

def my_func():
    global my_fruit
    my_fruit = 'orange'
    # print(name + ' loves my ' + my_fruit)

my_func()

print(my_fruit)
orange
number = 45 # defined outside a function

# can be accessed here
print(number)

def getSquare():
    # can also be accessed here
    print(number ** 2)

getSquare()
45
2025
#Local Scope

def add():
    number1 = 5
    number2 = 7
    summ = number1 + number2
    return summ

# print(add())
try: 
    print(summ)
except:
    print("summ is not defined")
summ is not defined
# Global Keyword

def add():
    global summ
    number1 = 5
    number2 = 7
    summ = number1 + number2
    return summ

add()

print(summ)
12
Back to top