Last active
November 11, 2020 03:56
-
-
Save PrudhviVajja/a1a6e6a10c6d66dfe4791ddb5038932f to your computer and use it in GitHub Desktop.
Classmethod Python decorator
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
class Datatypes(): | |
def __init__(self, *args): | |
self.args = list(args[0]) | |
def __call__(self): | |
print(self.args) | |
@classmethod | |
def from_list(cls, arglist): | |
args = tuple(arglist) | |
instance = cls(args) | |
return instance | |
@classmethod | |
def from_tuple(cls, argtuple): | |
args = argtuple | |
instance = cls(args) | |
return instance | |
@classmethod | |
def from_dict(cls, argdict): | |
args = tuple(argdict.values()) | |
instance = cls(args) | |
return instance | |
list_instance = Datatypes.from_list(["one", "two", "three"]) | |
tuple_instance = Datatypes.from_tuple(("one", "two", "three")) | |
dict_instance = Datatypes.from_dict({1:"one", 2:"two", 3:'three'}) | |
list_instance() # runs __call__ method in the class (by default). | |
tuple_instance() | |
dict_instance() | |
# Output | |
🌈 ››› python3 classmethod_example.py | |
['one', 'two', 'three'] | |
['one', 'two', 'three'] | |
['one', 'two', 'three'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment