问题
If I import a module and I want to iterate over the static methods therein, is there a way to do that?
In the module:
class duck():
@staticmethod
def duck_quack():
return 'Quacks like a duck'
@staticmethod
def person_walk():
return 'Walks like a person'
In the controller:
from applications.... import duck
m = duck()
def result_m():
for stuff in dir(m):
if 'person' in stuff:
result = stuff
elif 'duck' in stuff:
result = stuff
Instead, I keep getting a None
response. Is there a better way than using this?
回答1:
You are getting a None response because you are not returning anything. Methods that do not have a return statement return None.
I'm not sure what is the end goal of your approach, but I would do it thus:
obj = Duck()
def say_something(keyword):
return getattr(obj, keyword, None)
print(say_something('duck')())
Here is an example:
>>> class Foo(object):
... @staticmethod
... def duck():
... return 'Quak!'
... @staticmethod
... def person():
... return 'Hello'
...
>>> a = Foo()
>>> def say_something(thing):
... return getattr(a, thing, None)
...
>>> print(say_something('duck')())
Quak!
>>> print(say_something('person')())
Hello
getattr
will return None
by default (here I am explicitly passing it in as the third argument). Since you can't call None, you'll get this as a result:
>>> print(say_something('Foo')())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
So its best if you store the result and check that its not None
, or return some other callable:
>>> def say_something(thing):
... return getattr(a, thing, lambda: 'Not Found')
...
>>> say_something('duck')()
'Quak!'
>>> say_something('person')()
'Hello'
>>> say_something('foo')()
'Not Found'
回答2:
Your function has several problems:
- It doesn't take arguments, so you rely on scope for variable access;
- It doesn't
return
anything; and - If both methods are present, which one is
result
last depends on the order of keys in the dictionary.
Try:
def result_m(m):
for stuff in dir(m):
if 'person' in stuff:
result = stuff
elif 'duck' in stuff:
result = stuff
return result
and consider making an argument for the word to search for.
来源:https://stackoverflow.com/questions/24349080/how-to-iterate-over-class-methods