Checking class equality
In the previous exercise, you defined a BankAccount
class with a number
attribute that was used for comparison. But if you were to compare a BankAccount
object to an object of another class that also has a number
attribute, you could end up with unexpected results.
For example, consider two classes
|
|
Running acct == pn
will return True
, even though it compares a phone number with a bank account number.
It is good practice to check the class of objects passed to the __eq__()
method to make sure the comparison makes sense.
This exercise is part of the course
Introduction to Object-Oriented Programming in Python
Exercise instructions
- Modify the definition of
BankAccount
to only returnTrue
if thenumber
attribute is the same and thetype()
of both objects passed to it is the same. - Check if
acct
andpn
are equal.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
class BankAccount:
def __init__(self, number, balance=0):
self.number, self.balance = number, balance
def withdraw(self, amount):
self.balance -= amount
# Modify to add a check for the class type
def __eq__(self, other):
return (self.number == other.number) ____
acct = BankAccount(873555333)
pn = Phone(873555333)
# Check if the two objects are equal
print(____)