How to iterate over class methods

假如想象 提交于 2021-02-10 23:37:35

问题


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:

  1. It doesn't take arguments, so you rely on scope for variable access;
  2. It doesn't return anything; and
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!