Topic_5_Classes
Topic_5_Classes
Homework
Python Programming for Economics
Dr. Marcus Roel
Spring 2024, UNNC
Notes on Solution
Slides are becoming rather tricky to format in case of classes
See the notebook or html file
Standard Homework
go over our examples from the lecture and (1) understand them, and (2) vary them
slightly to see if you really understand them.
Classes
Experiment with classes by creating any object you find interesting. Afterwards,
create a parent class.
potential examples: a person, a student; a motor-vehicle, a car, a bus; a video
game weapon, a video game sword (or something less violent); an economic
agent, a consumer (solving your typical micro 1/2 problems); animals; flowers;
etc : )
think about potential things (verbs) these objects should be able to do.
Solution
My solution is a very simple person/student class, with minimal details
These are very much data-containers.
They have very little methods and thus are very uninteresting objects (they can't do
much without methods)
Do experiment with classes by creating any object you find interesting
If you haven't, try to search your particular example online.
Unless you were very creative, you can surely find it.
In [ ]: # My preferred module for working with time/dates. Check out doc!
from datetime import datetime
class Person:
""" A simple description of a person
Attributes:
first_name: first name
second_name: second name/family name
year_of_birth: year born
occupation: occupation
"""
self.occupation = occupation
def age(self):
# Not quite correct obviously. Would need full date of birth
return datetime.now().year - self.year_of_birth
# Feel free to implement this correctly.
# Hint: use a year, month, day day of birth attribute
# Or: Read datetime documentation to use datetime
def __str__(self):
return f"{self.first_name} {self.second_name}. Age: {self.age()}. Wo
In [ ]: class Student(Person):
""" A simple description of a student
Attributes:
first_name: first name
second_name: second name/family name
year_of_birth: year born
occupation: student
university: where student studies
major: student major
"""
def __str__(self):
return f"{self.first_name} {self.second_name}. Age: {self.age()}. Wo
In [ ]: # Testing Person Class
me = Person("Marcus", "Roel", 1986, "Feels like a CS Professor these days")
print(me)
Attributes:
width: the width of the rectangle
height: the height of the rectangle
"""
def get_area(self):
return self.width * self.height
def cut_in_half(self):
""" Cut the current rectangle in half
return: cut-away part of rectangle as a new Object"""
Solution to:
Calculate the area of the series of n rectangles where the next rectangle is half of
the previous.
In [ ]: def find_area_series_cut_rectangles(initial_height, initial_width, num_cuts)
rectangle = RectangleCutable(initial_height, initial_width)
area = rectangle.get_area()
for i in range(num_cuts):
rectangle = rectangle.cut_in_half()
area += rectangle.get_area()
return area
Area of a series of rectangles, with the first being a 1x1 square, the scond
a 0.5x1 rectangle is:
1.5
For: 1x1, 0.5x1, and 0.5x0.5, we have:
1.875
You could manually check whether these are right or use the classic formula that
calculates 1 + 1/2 + 1/4+. . . +(1/2)
n
Class Attributes
Create a class with a class attribute. Create an instance (a) of a class and check the
value of said attribute. Create another instance (b) of the class, and change the
class attribute for this instance. Check the value of the class attribute again for
instance a.
Class Attributes: Solution
In [28]: class class_attributes_test:
x = 10
a = class_attributes_test()
b = class_attributes_test()
print(f"a.x = {a.x}")
b.x = 20
a.x = 10
class StaticMethodExample:
@staticmethod
def add_two_numbers_static(a, b):
return a + b
# What happens if we also add a method without self but don't call it st
def add_two_numbers_no_self(a, b):
return a + b
In [ ]: class_static = StaticMethodExample()
a = 5
b = 6
In [ ]: # Calling a method via the instance of the class works for both
print(f"Add via staticmethod with instance. a = {a}, b = {b}")
print(f"a + b = {class_static.add_two_numbers_static(a, b)}")
# Calling a method via the class only works for the static method
print(f"Add via staticmethod with class. a = {a}, b = {b}")
print(f"a + b = {StaticMethodExample.add_two_numbers_static(a, b)}")
# Whereas non-static method without a self works when we call it via the cla
print(f"Add via no-self method with class. a = {a}, b = {b}")
print(f"a + b = {StaticMethodExample.add_two_numbers_no_self(a, b)}")—
def get_area(self):
return self.width * self.height
class Square(Rectangle):
def __init__(self, length):
# super().__init__(length, length) # Calls parent __init__
self.width = length
self.height = length
def get_diagonal(self):
return (2*self.width**2)**0.5 # recall: a**2 + b**2 = c**2
In [22]: my_square = Square(4)
print(f"Area = {my_square.get_area()}")
Area = 16
def get_diagonal(self):
# Notice the change. This will work!
return (2*self.length**2)**0.5
Diagonal = 5.656854249492381
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[27], line 1
----> 1 print(f"Area = {my_broken_square.get_area()}")
In [ ]: