programing

개체의 현재 속성 및 값을 모두 인쇄하는 기능이 내장되어 있습니까?

luckcodes 2023. 1. 1. 12:09

개체의 현재 속성 및 값을 모두 인쇄하는 기능이 내장되어 있습니까?

여기서 찾고 있는 것은 PHP의 print_r 함수입니다.

이것은, 문제의 오브젝트의 상태를 표시해, 스크립트를 디버깅 할 수 있도록 하기 위해서입니다.

싶다vars() mixed 에 섞어서.pprint():

from pprint import pprint
pprint(vars(your_object))

당신은 정말 다른 두 가지를 섞고 있군요.

또는 모듈을 사용하여 관심 있는 내용을 가져옵니다(사용하고 있습니다).__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__'}
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}

개체의 현재 속성 및 값을 모두 인쇄하는 기능이 내장되어 있습니까?

아니요. 가장 많이 업그레이드된 답변에는 일부 속성이 제외되며, 승인된 답변에는 공개되지 않은 API의 메서드 및 일부를 포함한 모든 속성을 가져오는 방법이 표시됩니다.단, 이 기능을 완전히 내장할 수 있는 기능은 없습니다.

즉, 사용자가 직접 작성할 수 있지만 퍼블릭 API의 일부인 속성 및 기타 계산된 데이터 설명자가 계산됩니다.이것을 원하지 않을 수도 있습니다.

from pprint import pprint
from inspect import getmembers
from types import FunctionType

def attributes(obj):
    disallowed_names = {
      name for name, value in getmembers(type(obj)) 
        if isinstance(value, FunctionType)}
    return {
      name: getattr(obj, name) for name in dir(obj) 
        if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}

def print_attributes(obj):
    pprint(attributes(obj))

다른 답변에 관한 문제

다양한 종류의 데이터 멤버를 가진 클래스에 대해 현재 가장 많이 투표된 답변이 적용되는지 확인합니다.

from pprint import pprint

class Obj:
    __slots__ = 'foo', 'bar', '__dict__'
    def __init__(self, baz):
        self.foo = ''
        self.bar = 0
        self.baz = baz
    @property
    def quux(self):
        return self.foo * self.bar

obj = Obj('baz')
pprint(vars(obj))

인쇄만:

{'baz': 'baz'}

★★★★★★★★★★★★★★★★★★vars 반환되는 것은__dict__하면 vars도 __dict__오브젝트 자체입니다.

vars(obj)['quux'] = 'WHAT?!'
vars(obj)

반환:

{'baz': 'baz', 'quux': 'WHAT?!'}

-- quux는 설정해서는 안 되는 속성이며 네임스페이스에 있어서는 안 되는 속성이기 때문에 좋지 않습니다.

현재 승인된 답변(및 기타)의 조언을 적용하는 것이 그다지 좋은 것은 아닙니다.

>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'bar', 'baz', 'foo', 'quux']

dir는 오브젝트와 관련된 모든 이름(실제로는 대부분)만 반환합니다.

inspect.getmembers코멘트에 기재되어 있는 ( )도 마찬가지로 결점이 있습니다.모든 이름과 값이 반환됩니다.

수업 시작

강의할 때 학생들에게 개체의 의미론적으로 공용 API를 제공하는 함수를 생성하게 합니다.

def api(obj):
    return [name for name in dir(obj) if name[0] != '_']

오브젝트의 의미 네임스페이스 복사본을 제공하도록 확장할 수 있지만 제외해야 합니다.__slots__ 「 속성진지하게 있는 는, 가 있습니다( 「가 아닌 으로 해석될 이 있기 때문입니다).「지금」은 「현재」가 아닙니다.

from types import FunctionType
from inspect import getmembers

def attrs(obj):
    disallowed_properties = {
        name for name, value in getmembers(type(obj)) 
        if isinstance(value, (property, FunctionType))
    }
    return {
        name: getattr(obj, name) for name in api(obj) 
        if name not in disallowed_properties and hasattr(obj, name)
    }

이제 속성인 quux를 계산하거나 표시하지 않습니다.

>>> attrs(obj)
{'bar': 0, 'baz': 'baz', 'foo': ''}

주의사항

하지만 우리는 우리의 부동산이 비싸지 않다는 것을 알고 있다.우리는 그것들을 포함하도록 논리를 바꾸고 싶을지도 모른다. 대신 다른 커스텀 데이터 기술자를 제외할 수도 있습니다.

그리고 이 기능을 더 커스터마이즈해야 합니다.그래서 우리가 원하는 것을 정확히 알고 제공하는 기능을 내장할 수 없다는 것은 말이 됩니다.이것은 우리가 직접 만들어야 하는 기능입니다.

결론

이 기능을 하는 빌트인 함수는 없습니다.따라서 상황에 가장 의미적으로 적합한 기능을 수행해야 합니다.

이를 위해서는 "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__방법들.Python 문서:

__repr__(self)에 의해 호출됩니다.repr()오브젝트의 "공식" 문자열 표현을 계산하기 위해 내장된 함수 및 문자열 변환(따옴표 포함)을 사용합니다.가능하다면, 이것은 (적절한 환경이 주어진) 동일한 값으로 개체를 다시 만드는 데 사용할 수 있는 유효한 Python 식처럼 보여야 합니다.이것이 불가능할 경우 "<..." 형식의 문자열을 입력합니다.유용한 설명...>"가 반환됩니다.반환 값은 문자열 개체여야 합니다.클래스가 repr()을 정의하지만 정의되지 않은 경우__str__() , , , 「 」__repr__()는 해당 클래스의 인스턴스를 "표준" 문자열로 표현해야 할 경우에도 사용됩니다.이것은 보통 디버깅에 사용되기 때문에 표현은 정보가 풍부하고 모호하지 않은 것이 중요합니다.

__str__(self)에 의해 호출됩니다.str()내장된 함수 및 인쇄문으로 객체의 "실행" 문자열 표현을 계산합니다.은 하다와 .__repr__()파이톤대신 보다 편리하거나 간결한 표현을 사용할 수 있습니다.반환 값은 문자열 개체여야 합니다.

확인해 볼 만한 가치가 있을 겁니다

Perl의 Data와 동등한 Python이 있습니까?덤퍼?

제가 추천하는 건...

https://gist.github.com/1071857

perl에는 Data::라는 이름의 모듈이 있습니다.오브젝트 데이터를 perl 소스 코드로 변환하는 덤퍼(NB: 코드를 소스로 변환하지 않으며, 거의 항상 출력의 오브젝트 메서드 함수로 변환하지 않습니다).이는 지속성을 위해 사용할 수 있지만 일반적인 목적은 디버깅입니다.

표준 python print가 달성하지 못하는 것이 많이 있습니다.특히 오브젝트의 인스턴스를 보고 오브젝트의 내부 16진 포인터를 제공하면 내림차순이 정지됩니다(err, 그 포인터는 전혀 쓸모가 없습니다).한마디로, 파이썬은 이 위대한 객체 지향 패러다임에 관한 것입니다만, 개봉 후 사용할 수 있는 툴은 객체 이외의 다른 것으로 작업할 수 있도록 설계되어 있습니다.

perl 데이터:Dumper를 사용하면 원하는 깊이를 제어할 수 있으며 원형 링크 구조도 탐지할 수 있습니다(이것은 매우 중요합니다).이 프로세스는 기본적으로 perl에서 실현하기 쉽습니다.이는 오브젝트에는 축복 이외의 특별한 마법이 없기 때문입니다(범용적으로 잘 정의된 프로세스).

를 사용하는 것을 추천합니다.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__.

의 경우, 「」를 하고,__dict__ ★★★★★★★★★★★★★★★★★」dir()원하는 정보를 얻을 수 있습니다.자세한 내용은 표준 라이브러리에 인스펙션모듈이 포함되어 있습니다.이 모듈을 사용하면 상세 정보를 얻을 수 있습니다.다음과 같은 정보가 실제로 제공되고 있습니다.

  • 함수 및 방법 매개 변수 이름
  • 클래스 계층
  • 함수/클래스 객체 구현 소스 코드
  • 프레임 객체의 로컬 변수

값 '내 오브젝트 속성 값'을 찾습니다dir() ★★★★★★★★★★★★★★★★★」__dict__아마 충분할 겁니다. 모든 의 오브젝트의 현재 하려면 , 「Python(피톤)」을 .inspect고려할 가치가 있다.

디버깅에 하고 싶은 , 스럽지 않습니다.에는 good가 하기 때문입니다.이치노__str__이미 구현되어 있습니다.그렇지 않으면 이 방법이 훨씬 효과적입니다.

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

쁘레티 사용

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)

출력:

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

메타프로그래밍 예: 매직이 있는 덤프 오브젝트:

$ 고양이 덤프.화이
#!/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 덤프 $.화이
<__main__.Data instance at 0x00A052D8>

Gnosis Utils의 경우:

$ python dump.py gnosis . 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>

조금 구식이지만 아직 작동 중입니다.

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))

그러면 모든 오브젝트 내용이 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)

왜 단순한 것이 아닐까요?

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

이것은 클래스 내, __init__ 내부 또는 외부 변수 정의에 관계없이 작동합니다.

your_obj = YourObj()
attrs_with_value = {attr: getattr(your_obj, attr) for attr in dir(your_obj)}

복잡한 데이터 구조의 모든 을 보려면 다음과 같이 하십시오.

from pprint import pprint
pprint(my_var)

여기서 my_var는 관심 변수입니다.사용했을 때pprint(vars(my_var))아무것도 얻지 못했고, 여기 있는 다른 답변들은 도움이 되지 않았거나 방법이 불필요하게 길어 보였어요.덧붙여서, 특히 제 경우, 제가 검사하고 있는 코드에는 사전이 들어 있었습니다.

않는 것으로 끝나는 .<someobject.ExampleClass object at 0x7f739267f400>출력의 종류입니다. 경우에는 하다'를 할 수도 요.__str__이치노

그리고 이걸 받은 한 가지 사례에서object, 「」, 「」,vars()해 보는 .따라서 두 가지 사례를 모두 다루는 더 나은 해결책은 두 가지 사례를 모두 개별적으로 시도하는 것입니다. ,, 을, 을, 용을 vars()예를 들어 예외적인 경우가 있습니다.TypeError: vars() argument must have __dict__ attribute.

서드파티 라이브러리가 없어도 모든 시나리오에서 사용할 수 있는 간단한 기능을 찾고 싶습니다.

일부 로그에 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=(',', ': ')))

vars()와 dir()를 시도했지만 둘 다 제가 찾던 것에 실패했습니다.vars()는 오브젝트에 __dict__(예외)가 없기 때문에 작동하지 않았습니다.TypeError:() vars 인수에는 __dict__ 속성이 필요합니다.dir()는 제가 찾던 것이 아닙니다.필드의 이름 리스트일 뿐 값이나 오브젝트 구조는 표시되지 않습니다.

default=json_serializer.default가 없는 대부분의 오브젝트에서 json.serializer()가 동작한다고 생각합니다만, 오브젝트에 datetime 필드가 있어서 표준 json 시리얼라이저가 실패했습니다.python으로 "datetime.datetime not JSON serializable"을 해결하는 방법을 참조하십시오.

고민하는 모든 분들을 위해

  • vars()모든 속성을 반환하지 않습니다.
  • dir()이치노

다음 코드는 모든 속성을 인쇄합니다.obj하다

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

삐삐인쇄만 해봐

오브젝트 변수 인쇄뿐만 아니라 다음과 같은 아름다운 출력에도 도움이 됩니다.

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

여러 가지 좋은 답변이 있지만, 속성에 AS 값을 부여할 수 있는 1-라이너는 다음과 같습니다.

(str(vars(config)).split(",")[1:])

여기서 'config'는 문제의 객체입니다.루프나 예쁜 프린트를 사용하지 않고 오브젝트의 관련 값(__main 등)만 인쇄하고 싶었을 뿐, 편리한 답변을 찾을 수 없었기 때문에 별도 답변으로 기재합니다.

pprint에는 데이터 구조를 미적으로 보기 좋게 표현하기 위한 "예쁜 프린터"가 포함되어 있습니다.포맷터는 해석자가 올바르게 해석할 수 있는 데이터 구조의 표현을 생성하며, 사람이 읽기에도 용이합니다.출력은 가능하면 한 줄에 유지되며 여러 줄로 분할될 경우 들여씁니다.

vars()는 이 객체의 Atribute를 표시하는 것처럼 보이지만 dir()는 부모 클래스의 Atribute도 표시하는 것처럼 보입니다.일반적으로 str, doc.dict 의 상속된 속성을 볼 필요가 없습니다.

In [1]: class Aaa():
...:     def __init__(self, name, age):
...:         self.name = name
...:         self.age = age
...:
In [2]: class Bbb(Aaa):
...:     def __init__(self, name, age, job):
...:         super().__init__(name, age)
...:         self.job = job
...:
In [3]: a = Aaa('Pullayya',42)

In [4]: b = Bbb('Yellayya',41,'Cop')

In [5]: vars(a)
Out[5]: {'name': 'Pullayya', 'age': 42}

In [6]: vars(b)
Out[6]: {'name': 'Yellayya', 'age': 41, 'job': 'Cop'}

In [7]: dir(a)
Out[7]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 ...
 ...
 '__subclasshook__',
 '__weakref__',
 'age',
 'name']

플라스크 디버깅툴바를 사용해 보세요.
https://pypi.python.org/pypi/Flask-DebugToolbarhttpspypi.python.org/pypi/

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)

답변에서 다음과 같이 개체의 '속성'만 가져오도록 약간 수정할 수 있습니다.

def getAttributes(obj):
    from pprint import pprint
    from inspect import getmembers
    from types import FunctionType
    
    def attributes(obj):
        disallowed_names = {
          name for name, value in getmembers(type(obj)) 
            if isinstance(value, FunctionType)}
        return {
          name for name in dir(obj) 
            if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}
    pprint(attributes(obj))

이 기능은 일시적으로 추가할 때 유용하며 기존 소스 코드를 많이 변경하지 않고 제거할 수 있습니다.

는 pprint를 값을 합니다.__repr__멤버 함수는 중첩된 개체로 재귀됩니다.python3에서 동작합니다.https://github.com/MoserMichael/pprintex 를 참조해 주세요.pip 경유로 인스톨 할 수 있습니다.pip install printex

python 오브젝트 내장형또는 값 조작을 좋아합니다.

메서드 또는 변수에 관계없이 속성의 경우:

o.keys()

이러한 속성의 값의 경우:

o.values()

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