your programing

객체의 현재 속성과 값을 모두 인쇄하는 내장 함수가 있습니까?

lovepro 2020. 9. 28. 09:50
반응형

객체의 현재 속성과 값을 모두 인쇄하는 내장 함수가 있습니까?


그래서 여기서 제가 찾고있는 것은 PHP의 print_r 함수 와 같은 것 입니다. 이것은 문제가되는 개체의 상태를 확인하여 스크립트를 디버깅 할 수 있도록하기위한 것입니다.


당신은 정말로 서로 다른 두 가지를 혼합하고 있습니다.

dir(), vars()또는 inspect모듈을 사용 하여 관심있는 것을 얻으십시오 ( __builtins__예로 사용합니다. 대신 어떤 객체도 사용할 수 있습니다).

>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__

원하는대로 사전을 인쇄하십시오.

>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...

또는

>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'DeprecationWarning',
...

>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
  'AssertionError': <type 'exceptions.AssertionError'>,
  'AttributeError': <type 'exceptions.AttributeError'>,
...
  '_': [ 'ArithmeticError',
         'AssertionError',
         'AttributeError',
         'BaseException',
         'DeprecationWarning',
...

예쁜 인쇄는 대화식 디버거에서 명령으로 사용할 수도 있습니다.

(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
                  'AssertionError': <type 'exceptions.AssertionError'>,
                  'AttributeError': <type 'exceptions.AttributeError'>,
                  'BaseException': <type 'exceptions.BaseException'>,
                  'BufferError': <type 'exceptions.BufferError'>,
                  ...
                  'zip': <built-in function zip>},
 '__file__': 'pass.py',
 '__name__': '__main__'}

당신은 다음과 vars()혼합 하고 싶습니다 pprint().

from pprint import pprint
pprint(vars(your_object))

def dump(obj):
  for attr in dir(obj):
    print("obj.%s = %r" % (attr, getattr(obj, attr)))

작성자의 선호도에 따라 예외 처리, 국가 / 특수 문자 인쇄, 중첩 된 개체로 반복 등을 추가하는 타사 기능이 많이 있습니다. 그러나 그들은 기본적으로 이것으로 요약됩니다.


dir 이 언급되었지만 속성 이름 만 제공됩니다. 값을 원한다면 __dict__를 시도하십시오.

class O:
   def __init__ (self):
      self.value = 3

o = O()

다음은 출력입니다.

>>> o.__dict__

{'value': 3}

이를 위해 "dir ()"함수를 사용할 수 있습니다.

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>

또 다른 유용한 기능은 도움말입니다.

>>> help(sys)
Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://www.python.org/doc/current/lib/module-sys.html

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known

개체의 현재 상태를 인쇄하려면 다음을 수행하십시오.

>>> obj # in an interpreter

또는

print repr(obj) # in a script

또는

print obj

클래스 정의 __str__또는 __repr__메소드. 로부터 파이썬 문서 :

__repr__(self)repr()내장 함수와 문자열 변환 (역 따옴표)에 의해 호출되어 객체의 "공식적인"문자열 표현을 계산합니다. 가능하다면 이것은 같은 값 (적절한 환경이 주어 졌을 때)을 가진 객체를 다시 만드는 데 사용할 수있는 유효한 파이썬 표현식처럼 보일 것입니다. 이것이 불가능한 경우 "<... 일부 유용한 설명 ...>"형식의 문자열이 반환되어야합니다. 반환 값은 문자열 개체 여야합니다. 클래스가 정의 경우 에 repr ()하지만 __str__(), 그 __repr__()클래스의 인스턴스의 "비공식"문자열 표현이 필요한 경우에도 사용됩니다. 이것은 일반적으로 디버깅에 사용되므로 정보가 풍부하고 모호하지 않은 표현이 중요합니다.

__str__(self)str()내장 함수와 print 문에 의해 호출되어 객체의 "비공식"문자열 표현을 계산합니다. 이것은 __repr__()유효한 파이썬 표현식이 아니어도된다는 점과 다릅니다 . 대신 더 편리하거나 간결한 표현이 사용될 수 있습니다. 반환 값은 문자열 개체 여야합니다.


체크 아웃 할 가치가 있습니다.

Perl의 Data :: Dumper와 동등한 Python이 있습니까?

제 추천은 이것입니다.

https://gist.github.com/1071857

perl에는 개체 데이터를 다시 perl 소스 코드로 변환하는 Data :: Dumper라는 모듈이 있습니다 (주의 : 코드를 다시 소스로 변환하지 않으며 거의 ​​항상 출력에서 ​​개체 메서드 함수를 원하지 않습니다). 지속성에 사용할 수 있지만 일반적인 목적은 디버깅입니다.

표준 파이썬 pprint가 달성하지 못하는 많은 것들이 있습니다. 특히 객체의 인스턴스를 볼 때 내림차순을 멈추고 객체의 내부 16 진 포인터를 제공합니다 (errr, 그 포인터는 방법). 간단히 말해서, 파이썬은이 훌륭한 객체 지향 패러다임에 관한 것이지만, 상자에서 꺼내는 도구는 객체 이외의 작업을 위해 설계되었습니다.

Perl Data :: Dumper를 사용하면 원하는 깊이를 제어 할 수 있으며 순환 연결된 구조도 감지 할 수 있습니다 (정말 중요합니다). 이 프로세스는 객체가 축복 (보편적으로 잘 정의 된 프로세스)을 넘어서는 특별한 마법이 없기 때문에 펄에서 근본적으로 쉽게 달성 할 수 있습니다.


대부분의 경우, 사용 __dict__또는 dir()당신이 원하는하고있는 정보를 얻을 것이다. 더 많은 세부 정보가 필요한 경우 표준 라이브러리에 inspect 모듈이 포함되어있어 인상적인 세부 정보를 얻을 수 있습니다. 실제 정보 중 일부는 다음과 같습니다.

  • 함수 및 메소드 매개 변수의 이름
  • 클래스 계층
  • 함수 / 클래스 객체 구현의 소스 코드
  • 프레임 객체의 지역 변수

당신은 단지를 찾고 있다면 "내 목적은 무엇 속성 값을 가질 수 있는가?", 다음 dir()__dict__아마 충분하다. 정말로 임의의 객체의 현재 상태를 파헤 치고 싶다면 (파이썬에서는 거의 모든 것이 객체라는 점을 명심하십시오) inspect고려할 가치가 있습니다.


매직을 사용한 메타 프로그래밍 예제 Dump 객체 :

$ cat dump.py
#!/usr/bin/python
import sys
if len(sys.argv) > 2:
    module, metaklass  = sys.argv[1:3]
    m = __import__(module, globals(), locals(), [metaklass])
    __metaclass__ = getattr(m, metaklass)

class Data:
    def __init__(self):
        self.num = 38
        self.lst = ['a','b','c']
        self.str = 'spam'
    dumps   = lambda self: repr(self)
    __str__ = lambda self: self.dumps()

data = Data()
print data

인수없이 :

$ python dump.py
<__main__.Data instance at 0x00A052D8>

시스 유틸리티 사용 :

$ python dump.py gnosis.magic MetaXMLPickler
<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject module="__main__" class="Data" id="11038416">
<attr name="lst" type="list" id="11196136" >
  <item type="string" value="a" />
  <item type="string" value="b" />
  <item type="string" value="c" />
</attr>
<attr name="num" type="numeric" value="38" />
<attr name="str" type="string" value="spam" />
</PyObject>

약간 구식이지만 여전히 작동합니다.


사용하는 것이 좋습니다 help(your_object).

help(dir)

 If called without an argument, return the names in the current scope.
 Else, return an alphabetized list of names comprising (some of) the attributes
 of the given object, and of attributes reachable from it.
 If the object supplies a method named __dir__, it will be used; otherwise
 the default dir() logic is used and returns:
 for a module object: the module's attributes.
 for a class object:  its attributes, and recursively the attributes
 of its bases.
 for any other object: its attributes, its class's attributes, and
 recursively the attributes of its class's base classes.

help(vars)

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.

그러면 모든 객체 내용이 json 또는 yaml 들여 쓰기 형식으로 재귀 적으로 출력됩니다.

import jsonpickle # pip install jsonpickle
import json
import yaml # pip install pyyaml

serialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional
print json.dumps(json.loads(serialized), indent=4)
print yaml.dump(yaml.load(serialized), indent=4)

from pprint import pprint

def print_r(the_object):
    print ("CLASS: ", the_object.__class__.__name__, " (BASE CLASS: ", the_object.__class__.__bases__,")")
    pprint(vars(the_object))

디버깅을 위해 이것을 사용하고 있고 모든 것을 재귀 덤프하고 싶다면 클래스에 __str__이미 좋은 구현 이 필요하기 때문에 허용되는 대답은 만족스럽지 않습니다 . 그렇지 않은 경우 훨씬 더 잘 작동합니다.

import json
print(json.dumps(YOUR_OBJECT, 
                 default=lambda obj: vars(obj),
                 indent=1))

일부 로그에 DEBUG 정보를 인쇄해야했는데 깨지기 때문에 pprint를 사용할 수 없었습니다. 대신 나는 이것을했고 거의 같은 것을 얻었습니다.

DO = DemoObject()

itemDir = DO.__dict__

for i in itemDir:
    print '{0}  :  {1}'.format(i, itemDir[i])

"myObject"를 덤프하려면 :

from bson import json_util
import json

print(json.dumps(myObject, default=json_util.default, sort_keys=True, indent=4, separators=(',', ': ')))

I tried vars() and dir(); both failed for what I was looking for. vars() didn't work because the object didn't have __dict__ (exceptions.TypeError: vars() argument must have __dict__ attribute). dir() wasn't what I was looking for: it's just a listing of field names, doesn't give the values or the object structure.

I think json.dumps() would work for most objects without the default=json_util.default, but I had a datetime field in the object so the standard json serializer failed. See How to overcome "datetime.datetime not JSON serializable" in python?


Try ppretty

from ppretty import ppretty


class A(object):
    s = 5

    def __init__(self):
        self._p = 8

    @property
    def foo(self):
        return range(10)


print ppretty(A(), show_protected=True, show_static=True, show_properties=True)

Output:

__main__.A(_p = 8, foo = [0, 1, ..., 8, 9], s = 5)

I've upvoted the answer that mentions only pprint. To be clear, if you want to see all the values in a complex data structure, then do something like:

from pprint import pprint
pprint(my_var)

Where my_var is your variable of interest. When I used pprint(vars(my_var)) I got nothing, and other answers here didn't help or the method looked unnecessarily long. By the way, in my particular case, the code I was inspecting had a dictionary of dictionaries.

Worth pointing out that with some custom classes you may just end up with an unhelpful <someobject.ExampleClass object at 0x7f739267f400> kind of output. In that case, you might have to implement a __str__ method, or try some of the other solutions. I'd still like to find something simple that works in all scenarios, without third party libraries.


pprint contains a “pretty printer” for producing aesthetically pleasing representations of your data structures. The formatter produces representations of data structures that can be parsed correctly by the interpreter, and are also easy for a human to read. The output is kept on a single line, if possible, and indented when split across multiple lines.


Why not something simple:

for key,value in obj.__dict__.iteritems():
    print key,value

Just try beeprint.

It will help you not only with printing object variables, but beautiful output as well, like this:

class(NormalClassNewStyle):
  dicts: {
  },
  lists: [],
  static_props: 1,
  tupl: (1, 2)

For everybody struggling with

  • vars() not returning all attributes.
  • dir() not returning the attributes' values.

The following code prints all attributes of obj with their values:

for attr in dir(obj):
        try:
            print("obj.{} = {}".format(attr, getattr(obj, attr)))
        except AttributeError:
            print("obj.{} = ?".format(attr))

You can try the Flask Debug Toolbar.
https://pypi.python.org/pypi/Flask-DebugToolbar

from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)

# the toolbar is only enabled in debug mode:
app.debug = True

# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = '<replace with a secret key>'

toolbar = DebugToolbarExtension(app)

I like working with python object built-in types keys or values.

For attributes regardless they are methods or variables:

o.keys()

For values of those attributes:

o.values()

참고URL : https://stackoverflow.com/questions/192109/is-there-a-built-in-function-to-print-all-the-current-properties-and-values-of-a

반응형