如何遍历类方法
如果我导入了一个模块,想要遍历里面的静态方法,有没有什么办法可以做到这一点呢?
在这个模块里:
class duck():
@staticmethod
def duck_quack():
return 'Quacks like a duck'
@staticmethod
def person_walk():
return 'Walks like a person'
在控制器里:
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
不过,我总是得到一个 None
的回应。有没有比这样做更好的方法呢?
2 个回答
1
你的函数有几个问题:
- 它没有接收参数,所以你只能依赖作用域来访问变量;
- 它没有
return
返回任何东西; - 如果两个方法都存在,那么
result
的最后值取决于字典中键的顺序。
试试:
def result_m(m):
for stuff in dir(m):
if 'person' in stuff:
result = stuff
elif 'duck' in stuff:
result = stuff
return result
并考虑为要搜索的单词添加一个参数。
3
你得到一个 None 的回应是因为你没有返回任何东西。没有返回语句的方法默认会返回 None。
我不太清楚你这个方法的最终目标是什么,但我会这样做:
obj = Duck()
def say_something(keyword):
return getattr(obj, keyword, None)
print(say_something('duck')())
这里有一个例子:
>>> 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
默认会返回 None
(这里我明确把它作为第三个参数传入)。因为你不能调用 None,所以你会得到这样的结果:
>>> print(say_something('Foo')())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
所以最好是把结果存起来,然后检查一下它是不是 None
,或者返回其他可以调用的东西:
>>> def say_something(thing):
... return getattr(a, thing, lambda: 'Not Found')
...
>>> say_something('duck')()
'Quak!'
>>> say_something('person')()
'Hello'
>>> say_something('foo')()
'Not Found'