不带dict的Python打印属性__

2024-04-26 17:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在为python编写桥脚本时遇到问题

我试图列出iTunes对象的属性

iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")

使用

>>> from pprint import pprint
>>> from Foundation import *
>>> from ScriptingBridge import *
>>> iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
>>> pprint (vars(iTunes))

我回来了

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute

有人知道怎么避开这个吗?


Tags: 对象fromimport脚本comapple属性vars
3条回答

尝试dir(iTunes)。它类似于vars,但更直接地用于对象。

这来得很晚,但对于另一个问题(但同样的错误),下面的方法对我有效:

json.dumps(your_variable)

确保在此之前已在脚本中导入了JSON。

import json

您需要找到一种以干净格式读取JSON的方法。

对于类似于vars(obj)的东西,当obj不能作为dict访问时,我使用这样的kludge:

>>> obj = open('/tmp/test.tmp')
>>> print vars(obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute
>>> print dict([attr, getattr(obj, attr)] for attr in dir(obj) if not attr.startswith('_'))

{'softspace': 0, 'encoding': None, 'flush': <built-in method flush of file object at 0xf7472b20>, 'readlines': <built-in method readlines of file object at 0xf7472b20>, 'xreadlines': <built-in method xreadlines of file object at 0xf7472b20>, 'close': <built-in method close of file object at 0xf7472b20>, 'seek': <built-in method seek of file object at 0xf7472b20>, 'newlines': None, 'errors': None, 'readinto': <built-in method readinto of file object at 0xf7472b20>, 'next': <method-wrapper 'next' of file object at 0xf7472b20>, 'write': <built-in method write of file object at 0xf7472b20>, 'closed': False, 'tell': <built-in method tell of file object at 0xf7472b20>, 'isatty': <built-in method isatty of file object at 0xf7472b20>, 'truncate': <built-in method truncate of file object at 0xf7472b20>, 'read': <built-in method read of file object at 0xf7472b20>, 'readline': <built-in method readline of file object at 0xf7472b20>, 'fileno': <built-in method fileno of file object at 0xf7472b20>, 'writelines': <built-in method writelines of file object at 0xf7472b20>, 'name': '/tmp/test.tmp', 'mode': 'r'}

我相信这是可以改进的,比如用if not callable(getattr(obj, attr)过滤掉函数:

>>> print dict([attr, getattr(obj, attr)] for attr in dir(obj) if not attr.startswith('_') and not callable(getattr(obj, attr)))
{'errors': None, 'name': '/tmp/test.tmp', 'encoding': None, 'softspace': 0, 'mode': 'r', 'closed': False, 'newlines': None}

相关问题 更多 >