2013-04-29 2 views
0

클래스를 정의하려면 __repr__ 메서드를 메서드가 아닌 모든 특성의 이름과 값만 쓰는 방식으로 정의하고 싶습니다. 어떻게해야합니까? 나는 이것을 이와 같이 작성했지만, 이것이 속성 유형을 검사하지 않는다는 것을 알았다.Python : 객체의 속성이 메소드인지 아닌지 어떻게 확인할 수 있습니까?

class Example: 
    def __repr__(self): 
     return "\n".join(["%s: %s" % (x, getattr(self, x)) for x in dir(self) if not x.startswith('__')]) 

여기에 누락 된 것은 속성 유형 검사입니다.

+0

이의 – defactodeity

답변

3

당신은 이런 식으로 뭔가를 inspect를 사용할 수는 :

from inspect import ismethod,getmembers 

class Example: 
    def __repr__(self): 
     return "\n".join("%s: %s" % (k, v) for (k,v) in getmembers(self,lambda x: not ismethod(x))) 

    def method(self): 
     return 1 

a = Example() 
a.foo = 'bar' 
print a 

이것은 또한 이중 밑줄 (__module__, __doc__) 속성을 선택합니다. 당신이 그들을 원하지 않는다면, 당신은 그들을 쉽게 필터링 할 수 있습니다.

+0

'@ property'와 클래스 변수도 가져올 것입니다. – kennytm

+0

나는이 두 경우를 모두 받아야한다고 주장 할 것이다. 확실히 속성 개체. 어쨌든 API 관점에서 볼 때 속성과 속성 간에는 아무런 차이가 없습니다 ...하지만 OP가 무엇을 원 하느냐에 따라 달라집니다. – mgilson

1

호출 내장 기능을 시도해보십시오 http://docs.python.org/2/library/functions.html#callable

+2

단점은 당신이 호출 개체 속성 만들 수 있다는 것입니다 :) 당신은 속성이 방법의 유형 인 경우 찾을 inspect.ismethod 사용할 수 있습니다'전자 = 예(); e.foo = lambda x : x * x' 예를 들어. – mgilson

+0

[변수가 인스턴스 메소드라고 주장하는 것이 더 낫다] (http://stackoverflow.com/a/1260997/1322401) (http://stackoverflow.com/questions/1259963/python-assert-that -variable-is-instance-method). –

1

당신은 또한 단지 인스턴스의 __dict__을 반복 할 수, __slots__을 정의하지 않는 클래스를 가정 (또는 vars() function를 통해).

class Superclass: 
    def __init__(self, w): 
     self.w = w 

class Example(Superclass): 
    def __init__(self, x, y, z): 
     super().__init__(1234) 
     self.x = x 
     self.y = y 
     self.z = z 

    @property 
    def x_prop(self): 
     return self.x 

    @classmethod 
    def do_something(cls, z): 
     return str(cls) + str(z) 

    def __call__(self): 
     return 4444 

    class_property = 42 


    def __repr__(self): 
     return "\n".join("%s: [%s]" % (k, v) for (k,v) in vars(self).items()) 

example = Example(2, lambda y: z, '4') 
example2 = Example(example, 6j, b'90') 

print(repr(example2)) 

이 인쇄

x: [x: [2] 
y: [<function <lambda> at 0x7f9368b21ef0>] 
z: [4] 
w: [1234]] 
y: [6j] 
z: [b'90'] 
w: [1234] 
관련 문제