找出给定对象的可用属性(和方法)的最佳方法是什么?

What is the best way to figure out available properties (and methods) of a given object?

我有这个简单的 for 我 运行 当我处理一个对象和文档时,好吧......还不够好。

for attr in dir(subreddit):
    print(attr, getattr(subreddit, attr))

上述方法有效,但是在调用某些方法后可能会添加一些可公开访问的属性。

例如使用实例Praw。如果我打电话给

print(subreddit.description)

在循环 运行 之前 subreddit 对象将具有 属性 subreddit.subscribersSubscribers 属性 但是如果 for 循环在调用 subreddit.description.

之前完成则不存在

由于 Praw 文档根本没有指定如何简单地阅读订阅者,我认为他们的文档中会有很多缺失。

重申一下,Praw 只是为了说明问题的真实示例:

找出给定对象的可用属性(和方法)的最佳方法是什么?

据我所知,dir是目前对一个对象的处理方式。来自 help(dir):

Help on built-in function dir in module builtins:

dir(...)
    dir([object]) -> list of strings

    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.

鉴于 Python 的动态特性,我几乎可以肯定不可能枚举属于一个实例的所有内容。它允许您随时向实例添加属性。

为了说明,请考虑以下代码:

# This class has nothing but the built-in methods
class MyClass:
    pass

mc = MyClass()

# so an instance of it has nothing but the built-in methods
print(dir(mc))

# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

# But, we can dynamically add things to the class:
mc.newattr = 'bob'

# now, `newattr` has been added.
print(dir(mc))

# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'newattr']

如您所见,标准 Python classes 对实例中可以看到的内容没有限制。您随意添加(和删除)属性和方法,dir 无法预测这一点。

如果您正在设计自己的代码,并希望停止这种行为,您可以定义 class 变量 __slots__:

下面是该代码的略微修改版本:

class MyClass:
    __slots__ = ['newattr']

mc = MyClass()

print(dir(mc))

mc.newattr = 'bob'

print(dir(mc))

mc.nextnew = 'sue'

# Traceback (most recent call last):
#   File "/Users/bkane/tmp.py", line 12, in <module>
#     mc.nextnew = 'sue'
# AttributeError: 'MyClass' object has no attribute 'nextnew'

但我不会为我不是从头开始设计的代码这样做。如果您删除它们动态修改实例结构的能力,某些库将无法工作。