dir和help在python中不显示对象的所有属性?

2024-10-01 09:26:32 发布

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

到目前为止,这是我的代码

import win32com.client as winc

outlook = winc.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()
print message.body

并且message.body打印我最后一封来自outlook的电子邮件。在

当我dir(message)help(message)时,body属性不来。为什么?在

^{pr2}$

为什么会这样?在

更新

有没有什么方法可以让我毫无疑问地了解一个对象的所有属性?


Tags: 代码importclientmessage属性applicationasbody
3条回答

尝试使用^{}方法。正如在docs中指定的那样,它列出了所有可写的属性,这样可能会有所帮助。在

根据本页http://docs.python.org/2/library/functions.html#dir

Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

因此,我们不应该依赖dir来了解一个对象的所有信息。如果该类实现__dir__方法,我们将只获得从该方法返回的任何内容。他们可能实现了__dir__,并从dir调用中抽象出{}。在

示例:

class TestClass:
    def __init__(self):
        self.myValue = 0
    def myMethod(self):
        pass
    def __dir__(self):
        return []

class TestClass1:
    def __init__(self):
        self.myValue = 0
    def myMethod(self):
        pass

print dir(TestClass())
print dir(TestClass1())

print dir(TestClass())
print dir(TestClass1())

输出

^{pr2}$

答案是NO,因为作为in this case,对象的__getattr__方法可以被重写。考虑以下示例:

>>> class Const(object):
...     def __init__(self, val):
...         self.value = val
...     def __getattr__(self, a):
...         return self.value
...     def __setattr__(self, a, v)
...         self.__dict__[a] = v
...
>>> c = Const(1)
>>> dir(c)
['__class__', '__delattr__', '__dict__',  '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'value']
>>> c.__dict__
{'value': 1}
>>> c.some_strange_attribute_name
1
>>> c.some_strange_attribute_name = 2
>>> c.some_strange_attribute_name
2

相关问题 更多 >