Matthieu Choplin
class Child(Parent):
# class body
class A:
def __init__(self, i = 0):
self.i = i
class B(A):
def __init__(self, j = 0):
self.j = j
def main():
b = B()
print(b.i)
print(b.j)
main()
Solution
Hide solution
Do not forget to call the __init__() method of the superclass
A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding.
__str__ is a special method used to represent the object
class Circle(GeometricObject):
# Override the __str__ method defined in GeometricObject
def __str__(self):
return super().__str__() + " radius: " + \
str(self.__radius)
For the class rectangle, override the class __str__ so that when I print a rectangle object it says "Rectangle of area 4 and perimeter 8"
Solution using "+" concatenation
Hide solution
def __str__(self):
return "Rectangle of area " + str(self.getArea()) +\
" and of perimeter " + str(self.getPerimeter())
Solution using format()
Hide solution
def __str__(self):
return "Rectangle of area {:.2f} and of perimeter {:.2f}".format(
self.getArea(), self.getPerimeter())
Many ways to format strings in python, see this website: https://pyformat.info/
def __str__(self):
return "color: " + self.__color + \
" and filled: " + str(self.__filled)
Dynamic binding works as follows: Suppose an object o is an instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C1 is the most specific class. In Python, Cn is the object class. If o invokes a method p, Python searches the implementation for the method p in C1, C2, ..., Cn-1 and Cn, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked.
You can find the full hierarchy on https://docs.python.org/3/library/exceptions.html#exception-hierarchy
See how we inherit from RunTimeError in the class InvalidRadiusException in the example CircleWithCustomException.py and how we use it in TestCircleWithCustomException.py
class C:
def __init__(self,x):
self.__x = x
def getX(self):
return self.__x
def setX(self, x):
self.__x = x
class C:
def __init__(self,x):
self.__x = x
class A(C):
def __init__(self):
super().__init__(2)
# Does not override C.__x
self.__x = 1
a = A()
print(a._A__x)
print(a._C__x)
class C:
def __init__(self,x):
self.setX(x)
def getX(self):
return self.__x
def setX(self, x):
if x < 0:
self.__x = 0
elif x > 1000:
self.__x = 1000
else:
self.__x = x
x = property(getX, setX)
class P:
def __init__(self,x):
self.x = x
@property
def x(self):
return self.__x
@x.setter
def x(self, x):
if x < 0:
self.__x = 0
elif x > 1000:
self.__x = 1000
else:
self.__x = x
Properties should only be used in cases where you actually need to perform extra processing on attribute access
class Person:
def __init__(self,supervisor):
self.supervisor = supervisor
class Child(ParentA, ParentB):
# rest of the class
Design a class named Account that contains:
NB: for making fields private, use this, remember that you can also use properties
Draw the UML diagram for the class, and then implement the class. (Hint: The method getMonthlyInterest() is to return the monthly interest amount, not the interest rate. Use this formula to calculate the monthly interest: balance * monthlyInterestRate.
monthlyInterestRate is annualInterestRate / 12. Note that annualInterestRate is a percent (like 4.5%). You need to divide it by 100.)
Write a test program that creates an Account object with an account id of 1122, a balance of £20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw £2,500, use the deposit method to deposit £3,000, and print the id, balance, monthly interest rate, and monthly interest.
Use the Account class created in the previous exercise to simulate an ATM machine. Create ten accounts in a list with the ids 0, 1, ..., 9, and an initial balance of £100. The system prompts the user to enter an id. If the id is entered incorrectly, ask the user to enter a correct id. Once an id is accepted, the main menu is displayed as shown in the sample run. You can enter a choice of 1 for viewing the current balance, 2 for withdrawing money, 3 for depositing money, and 4 for exiting the main menu. Once you exit, the system will prompt for an id again. So, once the system starts, it won't stop.
Show solution
Hide solution
See the file oop_account.pyand oop_atm.py
You can write a better program 😁