Last active
March 4, 2022 13:47
-
-
Save tom1299/a4377e3e9c9a0ac2a5171d00c52a3bc3 to your computer and use it in GitHub Desktop.
How to add a method to a class in code using python
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 Greeter: | |
pass | |
def create_greeting(name: str): | |
def greeting_method(self): | |
return print(f"Greetings {name}") | |
greeting_method.__name__ = f"greetings{name}" | |
return greeting_method | |
if __name__ == '__main__': | |
for name in ["Mary", "John", "Joe"]: | |
setattr(Greeter, f"greetings{name}", create_greeting(name)) | |
greeter = Greeter() | |
greeter.greetingsMary() | |
greeter.greetingsJohn() | |
greeter.greetingsJoe() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment