python - How to iterate over class methods -
if import module , want iterate on static methods therein, there way that?
in module:
class duck(): @staticmethod def duck_quack(): homecoming 'quacks duck' @staticmethod def person_walk(): homecoming 'walks person' in controller:
from applications.... import duck m = duck() def result_m(): stuff in dir(m): if 'person' in stuff: result = stuff elif 'duck' in stuff: result = stuff instead, maintain getting none response. there improve way using this?
you getting none response because not returning anything. methods not have homecoming statement homecoming none.
i'm not sure end goal of approach, thus:
obj = duck() def say_something(keyword): homecoming getattr(obj, keyword, none) print(say_something('duck')()) here example:
>>> class foo(object): ... @staticmethod ... def duck(): ... homecoming 'quak!' ... @staticmethod ... def person(): ... homecoming 'hello' ... >>> = foo() >>> def say_something(thing): ... homecoming getattr(a, thing, none) ... >>> print(say_something('duck')()) quak! >>> print(say_something('person')()) hello getattr homecoming none default (here explicitly passing in 3rd argument). since can't phone call none, you'll result:
>>> print(say_something('foo')()) traceback (most recent phone call last): file "<stdin>", line 1, in <module> typeerror: 'nonetype' object not callable so best if store result , check not none, or homecoming other callable:
>>> def say_something(thing): ... homecoming getattr(a, thing, lambda: 'not found') ... >>> say_something('duck')() 'quak!' >>> say_something('person')() 'hello' >>> say_something('foo')() 'not found' python python-2.7
No comments:
Post a Comment