2009-04-13 9 views

답변

3

"함수"가 의미하는 바에 달려 있습니다. 이런 식으로 뭔가하지만, 일할 수있는 그런 다음

import inspect 

def methods(c): 
    return (m for m in (getattr(c, d) for d in dir(c)) 
      if inspect.ismethoddescriptor(m) or inspect.ismethod(m)) 

:

여기
class C: 
    def f(self): pass 

>>> list(methods(C)) 
[<unbound method C.f>] 
+0

-1 return 문에 전체 표현식을 완전히 읽을 수 없게 만드는 경우. –

4

예, 가능합니다. 신속하고 더러운 : 당신이 더 세련 개념을하려면 unittest.py 모듈을 확인

class foo: 
    def one(self): 
     print "here is one" 
    def two(self): 
     print "here is two" 
    def three(self): 
     print "here is three" 


obj = foo() 
for entry in dir(obj): 
    print entry, callable(getattr(obj,entry)) 
    if callable(getattr(obj,entry)): 
     getattr(obj,entry)() 

. 문자열 "test"로 시작하는 모든 메서드를 실행하는 코드가 있어야합니다.

1

이 클래스의 기능을 통해 루프 수율을 사용하는 것입니다. 당신이 클래스를 쓴 이후

def get_functions(mod): 
    for entry in dir(mod): 
     obj=getattr(mod,entry); 
     if hasattr(obj, '__call__') and hasattr(obj,'__func__') : 
      yield obj 

class foo: 
    def one(self): 
     print ("here is two") 
     return 1 
    def two(self): 
     print ("here is two") 
     return 2 
    def three(self): 
     print ("here is three") 
     return 3 


print(sum([fun() for fun in get_functions(foo())])) 
1

, 당신은 이미 모든 기능을 알고있다.

class ThisIsPeculiar(object): 
    def aFunction(self, arg1): 
     pass 
    def anotherFunction(self, thisArg, thatArg): 
     pass 
    functionsToCall = [ aFunction, anotherFunction ] 

>>> p= ThisIsPeculiar() 
>>> p.functionsToCall 
[<function aFunction at 0x6b830>, <function anotherFunction at 0x6b870>] 
+0

그래,하지만 그게 너 자신을 반복하지 말라는 원칙에 위배된다. 게다가 그는 운동하려는 코드를 소유하지 않거나 불필요한 똥을 추가하고 싶지 않을 수 있습니다. –

+0

DRY에 위배되지 않는 것 같습니다. 자동으로 호출하지 않으려는 메소드를 쉽게 가질 수 있습니다. 이것은 호출 된 메소드 목록을 확실하게 식별합니다. –

1

inspect module 사용해보십시오 :

import inspect 

class Spam: 
    def eggs(self): 
     print "eggs" 
    def ducks(self): 
     print "ducks" 
    value = "value" 

spam = Spam() 
for name, method in inspect.getmembers(spam, callable): 
    method() 

출력 :

ducks 
eggs 
3

dir builtin 예를 들어, 객체의 모든 속성을 나열합니다 :

>>> class MyClass: 
...  def one(self): 
...   print "one" 
...  def two(self): 
...   print "two" 
...  def three(self): 
...   print "three" 
... 
>>> dir(MyClass) 
['__doc__', '__module__', 'one', 'three', 'two'] 

I을 t는

>>> c = MyClass() 
>>> dir(c) 
['__doc__', '__module__', 'one', 'three', 'two'] 

방법은 (c.attribute()를 통해) 호출 될 일이있는 속성입니다 .. 초기화 된 클래스에서 작동 - 우리가 변수를 통해 그 방법을 참조 할 getattr 기능을 사용할 수 있습니다 ..

>>> myfunc = getattr(c, 'one') 
>>> myfunc 
<bound method MyClass.one of <__main__.MyClass instance at 0x7b0d0>> 

그리고 우리는 단순히 변수를 호출 할 수 있습니다 ..

>>> myfunc() 
one # the output from the c.one() method 

일부 속성이 기능은 위의 예에서 (아니기 때문에,및 __module__). 그래서

>>> callable(c.three) 
True 
>>> callable(c.__doc__) 
False 

루프로 모든 것을 결합 : 그것은 호출 방법 (함수)의 경우 우리는 확인 우리에게 callable builtin을 할 수 있습니다, 이것은 다시 __init__ 같은 메소드를 호출 할 것이다 기억

>>> for cur_method_name in dir(c): 
...  the_attr = getattr(c, cur_method_name) 
...  if callable(the_attr): 
...    the_attr() 
... 
one 
three 
two 

하는 아마도 원하지 않을 것이다.cur_method_name을 밑줄로 시작하지 않고 건너 뛰고 싶을 수도 있습니다.

관련 문제