2010-07-11 1 views

답변

2

잘 Perl에서 Dumper는 당신에게 원래의 개체를 제공하는 인터프리터에 의해 eval 일 수있는 개체의 표현을 제공합니다. 파이썬에서 객체의 repr은 그것을 시도하고 때로는 가능합니다. dictrepr 또는 strrepr을 수행하고 datetimetimedelta과 같은 일부 클래스도이를 수행합니다. 그래서 reprDumper과 동등하지만 예쁜 것은 아니며 개체의 내부를 표시하지 않습니다. 이를 위해 dir을 사용하고 자신의 프린터를 굴릴 수 있습니다.

여기 eval -able 파이썬 코드 발생하지 않을 따라서 대신 오브젝트의 캐릭터를 생성하는 데 사용되어야하는 프린터에서 내 샷이다 : 위의 예에서

def dump(obj): 
    out = {} 

    for attr in dir(obj): 
    out[attr] = getattr(obj, attr) 

    from pprint import pformat 
    return pformat(out) 

class myclass(object): 
    foo = 'foo' 

    def __init__(self): 
    self.bar = 'bar' 

    def __str__(self): 
    return dump(self) 

c = myclass() 
print c 

을, 나는 무시했다 객체의 디폴트는 __str__입니다. __str__은 개체를 문자열로 나타내거나 문자열 서식 함수를 사용하여 서식을 지정하려고 할 때 호출됩니다.

BTW reprprint obj을 수행 할 때 인쇄되며, 해당 개체에 대해 __repr__ 메서드를 호출합니다. 개체의 서식을 제어하는 ​​방법에 대한 자세한 내용은 the Python documentation of __repr__을 참조하십시오.

# this would print the object's __repr__ 
print "%r" % c 

# this would print the object's __str__ 
print "%s" % c 

위의 코드의 출력은 정확히 자신, 내가 일반적으로 지금 수입이 덤퍼와 동등한 건너 온 많은이에 대한 대한 검색 후

{'__class__': <class '__main__.myclass'>, 
'__delattr__': <method-wrapper '__delattr__' of myclass object at 0xb76deb0c>, 
'__dict__': {'bar': 'bar'}, 
'__doc__': None, 
'__format__': <built-in method __format__ of myclass object at 0xb76deb0c>, 
'__getattribute__': <method-wrapper '__getattribute__' of myclass object at 0xb76deb0c>, 
'__hash__': <method-wrapper '__hash__' of myclass object at 0xb76deb0c>, 
'__init__': <bound method myclass.__init__ of <__main__.myclass object at 0xb76deb0c>>, 
'__module__': '__main__', 
'__new__': <built-in method __new__ of type object at 0x82358a0>, 
'__reduce__': <built-in method __reduce__ of myclass object at 0xb76deb0c>, 
'__reduce_ex__': <built-in method __reduce_ex__ of myclass object at 0xb76deb0c>, 
'__repr__': <method-wrapper '__repr__' of myclass object at 0xb76deb0c>, 
'__setattr__': <method-wrapper '__setattr__' of myclass object at 0xb76deb0c>, 
'__sizeof__': <built-in method __sizeof__ of myclass object at 0xb76deb0c>, 
'__str__': <bound method myclass.__str__ of <__main__.myclass object at 0xb76deb0c>>, 
'__subclasshook__': <built-in method __subclasshook__ of type object at 0x896ad34>, 
'__weakref__': None, 
'bar': 'bar', 
'foo': 'foo'} 
+0

고마워요! 이것은 나를 바른 길로 인도한다. –

관련 문제