DEV Community

Cover image for Polymorphism
Sam Salgado
Sam Salgado

Posted on

Polymorphism

Polymorphism Explained

Image description

Coding interviews use technical jargon for what is simply implementing the self-init function(def init(self)) or calling the same name with different signatures. The image above portrays a simple implementation of polymorphism within a class-based component. Here, we are calling into the class “Bitcoin” to obtain a {name}, {price}, {time}, and {date} using self.{}. After we ‘pass’ in the function, we call 4 variables of “b1”, “b2”, “b3”,
and “b4”. Finally, we print our four variables called to our above function values.
EX 2.
``
class BitcoinCharacteristics():
def currency(self):
print("Cryptocurrency")
def verification(self):
print("POW")
class ETHCharacteristics():
def currency(self):
print("Cryptocurrency")
def verification(self):
print("POS")

obj_btc = BitcoinCharacteristics()
obj_eth = ETHCharacteristics()
for char in (obj_btc, obj_eth):
char.currency()
char.verification()
``
Polymorphism can also work with two classes, like the one above. Instead of self-calling values, define each value in a print statement within a self-function. Below it, the “obj_btc” and “obj_eth” variables are equal to the class method above. A for loop will loop through our values for both Ethereum and Bitcoin. Notice how this implementation worked similarly to the first, a loop would not be necessary for one class of values, no matter the size.

Image description
Finally, let’s use inheritance so that our Bitcoin class can implement a subclass for Layer-2 Network Lightning. Inheritance in Python is when a subclass inherits from a parent class. Our subclass (Lightning_present) calls from the parent class(Lightning_past) via its “nodes” value. If we wanted, we could have multiple subclasses inherited from our parents. The major benefit of polymorphism is the ability to work with multiple data types efficiently.

Top comments (0)