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

时间:2017-09-19 18:01:50

标签: python praw

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

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

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

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

print(subreddit.description)
运行循环subreddit对象之前的

将具有属性subreddit.subscribers。如果在调用Subscribers之前完成for循环,则subreddit.description属性不存在。

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

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

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

1 个答案:

答案 0 :(得分:2)

据我所知,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类不会限制实例中可以看到的内容。您可以毫不费力地添加(和删除)属性和方法,而dir无法预测这一点。

如果您正在设计自己的代码,并希望停止此行为,则可以定义类变量__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'

但我不会那样做,因为我不是从头开始设计的。如果你删除了动态修改实例结构的能力,一些图书馆将无法工作。