Skip to content

Instantly share code, notes, and snippets.

@GammaGames
Created January 22, 2020 18:31
Show Gist options
  • Save GammaGames/6eb3ec3fa2dd1fa9f22d3d5a163d1413 to your computer and use it in GitHub Desktop.
Save GammaGames/6eb3ec3fa2dd1fa9f22d3d5a163d1413 to your computer and use it in GitHub Desktop.
Check if object has method and return function result
class Duck():
def quack(self):
print("quack!")
class Goose(Duck):
def quack(self):
print("honk!")
class Dog():
def bark(self, sound="bark"):
print(f"{sound}!")
def is_duck(target, function, *args, **kwargs):
if hasattr(target, function) and callable(getattr(target, function)):
return True, getattr(target, function)(*args, **kwargs)
else:
return False, None
if __name__ == "__main__":
print("Duck", "is" if is_duck(Duck(), "quack")[0] else "is not", "duck")
print("Goose", "is" if is_duck(Goose(), "quack")[0] else "is not", "duck")
print("Dog", "is" if is_duck(Dog(), "quack")[0] else "is not", "duck")
print("Dog", "is" if is_duck(Dog(), "quack", "woof")[0] else "is not", "duck with args")
print("Dog", "is" if is_duck(Dog(), "quack", sound="woof")[0] else "is not", "duck with kwargs")
print("Dog", "is" if is_duck(Dog(), "bark")[0] else "is not", "dog")
print("Dog", "is" if is_duck(Dog(), "bark", "woof")[0] else "is not", "dog with args")
print("Dog", "is" if is_duck(Dog(), "bark", sound="woof")[0] else "is not", "dog with kwargs")
@GammaGames
Copy link
Author

Output looks like so:

quack!
Duck is duck
honk!
Goose is duck
Dog is not duck
Dog is not duck with args
Dog is not duck with kwargs
bark!
Dog is dog
woof!
Dog is dog with args
woof!
Dog is dog with kwargs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment