| Dunder Method | Invoking Expression |
|---|---|
| __init__ | Constructor
call, e.g., p = Person("Alice", "F", 11) |
| __str__ | str(p) or print(p) |
| __repr__ | repr(p) |
| __lt__ | p < q |
| __eq__ | p == q |
# In class, we sorted by age:
def __lt__(self, other):
return self.age < other.age
# To sort in alphabetic order by name:
def __lt__(self, other):
return self.name < other.name
# In test3.py, to sort with either __lt__ method:
persons.sort( )
print(persons)
#__lt__ method for Card class.
def __lt__(self, other):
return self.rank < other.rank
# __eq__ method for Card class
def __eq__(self, other):
return self.rank == other.rank
# Unit test script test2.py to test == operator:
import card
import unittest
class MyUnitTestClass(unittest.TestCase):
def test_1(self):
c = card.Card(12, 'H') #<-- QH
d = card.Card(12, 'S') #<-- QS
e = card.Card(14, 'C') #<-- AC
self.assertEqual(c == d, True)
self.assertEqual(d == e, False)
if __name__ == '__main__':
unittest.main( )
# p is a Person object. p.have_birthday( ) # q is a Pet object. q.set_vaccinated(True)
Person.have_birthday(p) Pet.set_vaccinated(q, True)
def have_birthday(self):
self.age += 1
def set_vaccinated(self, v):
self.vaccinated = v
=== animal.py ================================
# Add this method to the Animal class obtained
# from the PetsDict Example:
def __repr__(self):
return f'<{str(self)}>'
=== test1.py =================================
from animal import Animal
a = Animal("dog", "German Shephard", "M")
print(a)
print(a.animal_type, a.breed, a.gender)
=== test2.py =================================
from animal import Animal
import unittest
class MyUnitTestClass(unittest.TestCase):
def test_animal(self):
a = Animal("dog", "German Shephard", "M")
self.assertEqual(str(a), "dog German Shephard M")
self.assertEqual(a.animal_type, "dog")
self.assertEqual(a.breed, "German Shephard")
self.assertEqual(a.gender, "M")
if __name__ == '__main__':
unittest.main( )
=== test3.py =================================
from animal import Animal
animals = [ ]
fin = open("animals.txt", "r")
# Throw away first line
fin.readline( )
for line in fin:
fields = line.split(',')
a = Animal(fields[0], fields[1], fields[2])
animals.append(a)
print(animals)
class B(A): ... Put class definition for B here.
class MyUnitTestClass(unittest.TestCase):
| Class A | Class B |
|---|---|
| Base Class | Derived Class |
| Superclass | Subclass |
| Parent Class | Child Class |