객체의 변수&속성을 출력하는 방법

조회수 9499회

파이썬에는 PHPprint_r같은 함수가 있나요? 디버그 할 때 object의 상태를 봐야해서요. 비슷한 기능 있을까요?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    dir(), vars()를 써보세요

    dir()

    • 인자가 주어지지 않으면 현재 local scope에 있는 name을 저장한 listreturn해줍니다.
    • 인자가 주어진 경우엔 그 object에 있는 attributestring형태로 저장한 listreturn해줍니다.
    • objectmodule object인 경우, 리스트는 모듈의 어트리뷰트 이름을 저장하고 있습니다.
    • objecttype이나 class object인 경우, 리스트는 해당 클래스와 base클래스들의 어트리뷰트 이름을 저장하고 있습니다.

    • object__dir__()를 지원하지 않으면, 대신 __dict__ 어트리뷰트 등에서 정보를 모아옵니다.

    • object안에서 __getattr__()을 따로 정의한 경우에는 dir()returnlist는 완전하지 않을 수도 있습니다

    • list의 원소는 알파벳 순서로 정렬되어있습니다

    vars()module, class, instance, 그 외 __dict__ 어트리뷰트가 있는 object__dict__ 어트리뷰트를 return해줍니다.

    class myClass(object):
        def __init__(self):
            pass
        def myFunc1(self):
            pass
    
    
    from pprint import pprint
    l = dir(myClass)
    
    print "---print l---"
    print l
    
    print "\n\n---pprint(l)---"
    pprint(l)
    
    print "\n\n---pprint(l, indent=2)---"
    pprint(l, indent=2)
    

    결과)

    ---print l---
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'myFunc1']
    
    
    ---pprint(l)---
    ['__class__',
     '__delattr__',
     '__dict__',
     '__doc__',
     '__format__',
     '__getattribute__',
     '__hash__',
     '__init__',
     '__module__',
     '__new__',
     '__reduce__',
     '__reduce_ex__',
     '__repr__',
     '__setattr__',
     '__sizeof__',
     '__str__',
    '__subclasshook__',
     '__weakref__',
     'myFunc1']
    
    
    ---pprint(l, indent=2)---
    [ '__class__',
      '__delattr__',
      '__dict__',
      '__doc__',
      '__format__',
      '__getattribute__',
      '__hash__',
      '__init__',
      '__module__',
      '__new__',
      '__reduce__',
      '__reduce_ex__',
      '__repr__',
      '__setattr__',
      '__sizeof__',
      '__str__',
      '__subclasshook__',
      '__weakref__',
      'myFunc1']
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)