Created
December 4, 2021 20:32
-
-
Save adililhan/d9afbb1ef518f6885c6485eb53037145 to your computer and use it in GitHub Desktop.
Alternative 2 - Constructor overloading in Python 3.8 and Afterwards
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
class Computer: | |
@functools.singledispatchmethod | |
def __init__(self, *parts): | |
self.parts = " *** ".join(parts) | |
def get_parts(self): | |
return self.parts | |
@Computer.__init__.register | |
def __init__(self, parts: dict): | |
self.parts = parts.items() | |
@Computer.__init__.register | |
def __init__(self, parts: list): | |
self.parts = " - ".join(parts) | |
@Computer.__init__.register | |
def __init__(self, parts: int): | |
self.parts = parts | |
pc1 = Computer("BIOS", "Power supply") | |
pc2 = Computer({"CPU": "3.0GHz", "RAM": "32GB"}) | |
pc3 = Computer(["CPU", "RAM", "SSD"]) | |
pc4 = Computer("Motherboard") | |
pc5 = Computer(99999) | |
print(pc1.get_parts()) | |
print(pc2.get_parts()) | |
print(pc3.get_parts()) | |
print(pc4.get_parts()) | |
print(pc5.get_parts()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An alternative approach: https://gist.github.com/adililhan/c4c50608a9c12e9e625fadbe4873a871
Another alternative approach: https://gist.github.com/adililhan/b7b050bf84357a5a529385c44921f8d3