Created
January 22, 2020 18:31
-
-
Save GammaGames/6eb3ec3fa2dd1fa9f22d3d5a163d1413 to your computer and use it in GitHub Desktop.
Check if object has method and return function result
This file contains hidden or 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 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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output looks like so: