Python Class Exercises

Let’s check out some exercises that will help understand Classes better.

Exercise 4-a: Simple Class Attributes (name and origin)

A class regarding an imaginary jet inventory is already defined for you. Also an instant of this Jet class is created and assigned to variable first_item.

Print the name of the first_item.


You can call the name attribute with adding it to an instance of the class such as:

anyinstance.name

a=first_item.name

Exercise 4-b: Simple attribute (origin)

This time print the origin of the first_item.


Origin attribute can simply be shown as:

self.origin

b=first_item.origin

Exercise 4-c: Jet Fighter Instances

Create new instances until the sixth item following this order: F14, SU33, AJS37, Mirage2000, Mig29, A10. You can check Hint 1 for the origins.


SU33: Russia
AJS37: Sweden
Mirage2000: France
F14: USA
Mig29: USSR
A10: USA

You can create an instance as following:

first_item=Jet(name, country)

first_item=Jets("F14", "USA")
second_item=Jets("SU33", "Russia")
third_item=Jets("AJS37", "Sweden")
fourth_item=Jets("Mirage2000", "France")
fifth_item=Jets("Mig29", "USSR")
sixth_item=Jets("A10", "USA")

Exercise 4-d: Jet Fighter Inventory

Add another attribute called "quantity" to the initialization method (usually referred to as constructor or __init__). Then define assign this attribute to self.quantity attribute inside the constructor.

Then create 2 instances for: F14 and Mirage2000 with quantities 87 and 35.


You can add quantity parameter to your constructor as following:

    def __init__(self, name, country, quantity):

Then you’ll need to assign this parameter to a self attribute so that there is a meaningful connection between the parameter and attribute.

Pay attention to how method definition def needs to start with indention because it’s inside class definition. Indention is a big characteristic of Python programming and space characters matter in Python codes. 1 indention normally equals 4 space character (sometimes 1 tab character depending on the platform you’re coding).

You can add quantity parameter to your constructor as following:

def __init__(self, name, country, quantity):

    self.name = name
    self.origin = country
    self.origin = quantity

Then you’ll need to assign this parameter to a self attribute so that there is a meaningful connection between the parameter and attribute.

You can create instances of Jet class as below:
first_item=Jets("F14","USA",87)
second_item=Jets("Mirage2000","France",35)
And finally, all you need to do is do simple algebra with quantity attribute of the instances.
total = first_item.quantity+second_item.quantity

Exercise 4-e: Nobel Peace Prize goes to Bangladesh

Let's try something else.


Try building a simple class from the ground up. An instance is already created for you and instance attributes are included inside the print. Take those clues and try to reverse engineer the class.


Muhammad Yunus and Grameen Bank received the Nobel Peace Prize in 2006. Grameen Bank is a community development bank founded by Muhammad Yunus in 1983 in Bangladesh. Sometimes referred to as “the bank for the poor”, Grameen Bank made significant contributions to small businesses and individual entrepreneurs since its foundation, you can check out their website here.

The documentary film Living on One Dollar features Grameen Bank’s microcredit operation in a rural Guatemalan village. This film used to be available on Netflix also but country restrictions may apply.

This year’s Nobel Prize winners will be announced in October as published in this announcement here.

class Nobel:

    def __init__(self, category, year, winner):
        self.category = category
        self.year = year
        self.winner = winner

Exercise 4-f: String Representation of Python Classes

Let's practice using string representation method to represent the data in previous exercise in a much "classier" way, no pun intended!.


__str__ function can be used to return a string representation for the class when needed.


This time we will look at the Turing prize. Everything is pretty much created for you. There is a class named Turing and there is an instance named tu2022. Now add something so that when instance is printed directly, it prints: Robert Metcalfe was the winner of Turing Prize in 2022. Of course, it should work the same for any instance of this class, so no hard coding!


First thing first, you need to initiate your class with the help of initiation method (constructor) shown below as __init__:

class Turing:

    def __init__(self, category, year, winner):
        self.category = category
        self.year = year
        self.winner = winner

String representation method can be included using __str__ method.

Make sure you include return statement inside your string representation method.

def __str__(self):
return "{} was the winner of Turing Prize in {}".format(self.winner, self.year)

After this implementation, you will be able to directly print the instance you created. And thanks to string representation you will get a meaningful output as you’ve programmed inside your string representation method.

class Turing:

    def __init__(self, category, year, winner):
        self.category = category
        self.year = year
        self.winner = winner

    def __str__(self):
        return "{} was the winner of Turing Prize in {}".format(self.winner, self.year)

tu2022=Turing("Network", 2022, "Robert Metcalfe")
print(tu2022)

Exercise 4-g: String Representation of Python Classes

We have seen multiple examples of class usage in Python. Let's build something from ground up.


In this exercise create a class named myfunc and inside it place a very simple function named "fifth" which takes x and returns fifth power of x. No __init__ or class attributes needed.


Finally call your function with number 5 and assign it to variable ans.

You can use ** operator to raise numbers to a power in Python.

Here, you can read more about Python Operators.

You can simply create a function with an x parameter as below.

Make sure you include return statement inside your function.

    def fifth(x):
        return x**5

Now, all you have to do is to place this function inside a class and don’t forget to use indentation, for that you can select multiple lines and press tab once.

class myfunc:

    def fifth(x):
        return x**5

ans = myfunc.fifth(5)

Exercise 4-h: String Representation of Python Classes

Now let's make some changes to the class we created in the previous Python exercise.


First make your function so that it takes to parameters: x and y. x will be the number being raised and y will be the power. So, users can raise numbers to any power! Also let's change the function's name to power.


Also let's add a string representation quickly, so that when a user prints the class they get a meaningful description.


It can be something like: This class will consist of mathematical operations. We only have one function named power currently.

You can use ** operator to raise numbers to a power in Python.

Here, you can read more about Python Operators.

We need a slight modification to our function as below:

    def power(x,y):
        return x**y

Now, let’s place it inside a class named myfunc.

You can simply add a string representation as below:

    def __str__(self):
        return "mMyfunc is a class which is capable of mathematical operations like raising a number to a power with power function."

 

class myfunc:

    def power(x,y):
        return x**y

    def __str__(self):
        return "mMyfunc is a class which is capable of mathematical operations like raising a number to a power with power function."

ans1 = myfunc.power(5, 6)
ans2 = myfunc()