Skip to content

Instantly share code, notes, and snippets.

@msyvr
Created September 15, 2021 00:22
Show Gist options
  • Save msyvr/58f5068348bfeb76f13ab29eeeabac8a to your computer and use it in GitHub Desktop.
Save msyvr/58f5068348bfeb76f13ab29eeeabac8a to your computer and use it in GitHub Desktop.
python polymorphism: with inheritance objects, methods follow priority order behaviour as defined in: 1. object class, 2. parent class
class IrishPostalAddress(BasePostalAddress):
def __init__(self, recipient, postalCode):
super().__init__("IRELAND", recipient)
self.postalCode = postalCode
def display(self):
print(self.recipient)
print(self.postalCode)
print(self.country)
def validate(self):
return super().validate() and len(self.postalCode) == 7
class USPostalAddress(BasePostalAddress):
def __init__(self, recipient, street, city, state, zipcode):
super().__init__("USA", recipient)
self.street = street
self.city = city
self.state = state
self.zip = zipcode
def display(self):
print(self.recipient)
print(self.street)
print(self.city + ", " + self.state + " " + self.zip)
print(self.country)
def validate(self):
return (super().validate() and self.city != '' and
len(self.state) == 2 and
(len(self.postalCode) == 5 or len(self.postalCode) == 9))
addrList = [IrishPostalAddress("Alf Jones", "A26F4G9"),
USPostalAddress("Abe Jones", "103 Anywhere Ln",
"Greenville", "SC", "29609"),
IrishPostalAddress("Gabe Jones", "A65F4E2")]
for addr in addrList:
addr.display()
# from https://runestone.academy/runestone/books/published/thinkcspy/Inheritance/07-CaseStudy.html
# find out if the object belongs to a specific class. Python provides the isinstance() function for this purpose. isinstance() is designed for situations where you want to access a field or invoke a method on an object, but you want to do so only if the object provides the needed functionality. Given an object obj and a class cls, isinstance(obj, cls) returns True if obj is an instance of cls (or a subclass of cls), and False if it is not.
# like inheritance itself, isinstance() should be used sparingly. Code that invokes isinstance() is often performing work on an object that the object should be designed to do itself, and is not utilizing inheritance and polymorphism to its full potential.
for addr in addrList:
if isinstance(addr, USPostalAddress) and addr.city == 'Greenville':
addr.display()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment