문제

파이썬 객체의 방법을 반복하여 호출하는 올바른 방법은 무엇입니까?

주어진 개체 :

class SomeTest():
  def something1(self):
    print "something 1"
  def something2(self):
    print "something 2"

올바른 솔루션이 없습니다

다른 팁

검사 모듈을 사용하여 클래스 (또는 인스턴스) 멤버를 얻을 수 있습니다.

>>> class C(object):
...     a = 'blah'
...     def b(self):
...             pass
... 
...
>>> c = C()
>>> inspect.getmembers(c, inspect.ismethod)
[('b', <bound method C.b of <__main__.C object at 0x100498250>>)]

GetMembers ()는 각 튜플이 (이름, 멤버) 인 튜플 목록을 반환합니다. getMembers ()에 대한 두 번째 인수는 술어입니다.

방법 대 기능 및 기타 유형의 부름 ...

(Unknown의 게시물의 주석의 문제를 해결하기 위해.)

먼저, 사용자 정의 메소드 외에도 내장 된 방법이 있으며 Doc과 마찬가지로 내장 방법이 있습니다. http://docs.python.org/reference/datamodel.html "실제로 내장 함수의 다른 변장"(C 함수 주변의 래퍼입니다.)

Unknown의 인용 인용문과 같이 사용자 정의 방법은 다음과 같이 말합니다.

사용자 정의 메소드 개체는 클래스, 클래스 인스턴스 (또는 없음) 및 호출 가능한 객체 (일반적으로 사용자 정의 함수)를 결합합니다.

그러나 이것이 "정의하는 것은 __call__ 객체에 첨부 된 방법은 메소드입니다. "메소드는 호출 가능이지만 호출 가능은 반드시 메소드가 아닙니다. 사용자 정의 메소드는 견적이 말한 내용을 둘러싼 래퍼입니다.

바라건대이 출력 (내가 편리한 Python 2.5.2에서)은 차이점을 보여줄 것입니다.

IDLE 1.2.2      
>>> class A(object):
    x = 7


>>> A  # show the class object
<class '__main__.A'>
>>> a = A()
>>> a  # show the instance
<__main__.A object at 0x021AFBF0>
>>> def test_func(self):
    print self.x


>>> type(test_func)  # what type is it?
<type 'function'>
>>> dir(test_func)  # what does it have?
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__',
 '__getattribute__', '__hash__', '__init__', '__module__', '__name__',
 '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict',
 'func_doc', 'func_globals', 'func_name']
>>> # But now let's put test_func on the class...
>>> A.test = test_func
>>> type(A.test)  # What type does this show?
<type 'instancemethod'>
>>> dir(A.test)  # And what does it have?
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__',
 '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class',
 'im_func', 'im_self']
>>> # See, we just got a wrapper, and the function is in 'im_func'...
>>> getattr(A.test, 'im_func')
<function test_func at 0x0219F4B0>
>>> # Now to show bound vs. unbound methods...
>>> getattr(a.test, 'im_self') # Accessing it via the instance
<__main__.A object at 0x021AFBF0>
>>> # The instance is itself 'im_self'
>>> a.test()
7
>>> getattr(A.test, 'im_self') # Accessing it via the class returns None...
>>> print getattr(A.test, 'im_self')
None
>>> # It's unbound when accessed that way, so there's no instance in there
>>> # Which is why the following fails...
>>> A.test()

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    A.test()
TypeError: unbound method test_func() must be called with A instance as
first argument (got nothing instead)
>>>

및 - 다음 추가 출력을 추가하기 위해 편집 하는데도 관련이 있습니다 ...

>>> class B(object):
    pass

>>> b = B()
>>> b.test = test_func  # Putting the function on the instance, not class
>>> type(b.test)
<type 'function'>
>>> 

더 많은 출력을 추가하지는 않지만 클래스를 다른 클래스 또는 인스턴스의 속성으로 만들 수 있으며, 클래스가 호출 가능하더라도 메소드를 얻지 못할 것입니다. 메소드는 비 Data 디스크립터를 사용하여 구현되므로 작동 방식에 대한 자세한 정보를 원한다면 설명자를 찾으십시오.

이 코드 스 니펫은 찾을 수있는 모든 것을 호출합니다. obj 매핑 결과 저장 결과, 여기서 키는 속성 이름입니다. dict((k, v()) for (k, v) in obj.__dict__.iteritems() if k.startswith('something'))

편집하다

다니엘, 당신은 틀 렸습니다.

http://docs.python.org/reference/datamodel.html

사용자 정의 방법

사용자 정의 방법 물체 클래스, 클래스 인스턴스를 결합합니다 (또는 없음) 및 모든 호출 가능한 개체 (일반적으로 사용자 정의 함수).

따라서 __call__를 정의하고 객체에 첨부되는 것은 메소드입니다.

대답

객체의 요소가 어떤 요소가 있는지 확인하는 적절한 방법은 DIR () 함수를 사용하는 것입니다.

분명히이 예는 논증을 취하지 않는 기능에만 적용됩니다.

a=SomeTest()
for varname in dir(a):
    var = getattr(a, varname)
    if hasattr(var, "__call__"):
        var()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top