Python 找出给定对象的可用属性(和方法)的最佳方法是什么?
我在处理一个对象和文档时运行了一个简单的Python 找出给定对象的可用属性(和方法)的最佳方法是什么?,python,praw,Python,Praw,我在处理一个对象和文档时运行了一个简单的for。。。这还不够好 for attr in dir(subreddit): print(attr, getattr(subreddit, attr)) 上面的方法是有效的,但是在调用某个方法之后,可能会添加一些可公开访问的属性 例如,使用Praw的实例。如果我打电话 print(subreddit.description) 在运行循环subreddit对象之前,该对象将具有属性subreddit.subscribersSubscribers
for
。。。这还不够好
for attr in dir(subreddit):
print(attr, getattr(subreddit, attr))
上面的方法是有效的,但是在调用某个方法之后,可能会添加一些可公开访问的属性
例如,使用Praw
的实例。如果我打电话
print(subreddit.description)
在运行循环subreddit
对象之前,该对象将具有属性subreddit.subscribers
<但是,如果在调用subreddit.description
之前完成了for循环,则code>Subscribers属性不存在
由于Praw
documentation根本没有指定如何简单地读取订阅者,我认为他们的文档中会缺少很多内容
重申一下,Praw
只是为了举例说明问题的实质:
找出给定对象的可用属性(和方法)的最佳方法是什么?据我所知,
dir
是在当前时刻对对象执行此操作的方法。从帮助(目录)
:
我几乎可以肯定,鉴于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
无法预测这一点
如果您正在设计自己的代码,并且希望停止此行为,则可以定义类变量:
下面是该代码的一个稍加修改的版本:
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'
class-MyClass:
__时隙\uuu1=['newattr']
mc=MyClass()
印刷(dir(mc))
mc.newattr='bob'
印刷(dir(mc))
mc.nextnew='sue'
#回溯(最近一次呼叫最后一次):
#文件“/Users/bkane/tmp.py”,第12行,在
#mc.nextnew='sue'
#AttributeError:“MyClass”对象没有属性“nextnew”
但我不会这样做,因为我不是从头开始设计代码的。如果您删除一些库动态修改实例结构的功能,它们将无法工作。您询问的是内省这一一般主题的一个方面,对此有很多介绍。是其中一个以你的问题的答案开始的。
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'