Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tom1299/a4377e3e9c9a0ac2a5171d00c52a3bc3 to your computer and use it in GitHub Desktop.
Save tom1299/a4377e3e9c9a0ac2a5171d00c52a3bc3 to your computer and use it in GitHub Desktop.
How to add a method to a class in code using python
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