我有一个简单的for
当我处理一个对象和文档时,我会运行,嗯。。。还不够好
for attr in dir(subreddit):
print(attr, getattr(subreddit, attr))
不过,上面的方法是可行的,在调用某个方法之后,可能会添加一些可公开访问的属性
例如,使用Praw
的实例。如果我打电话
print(subreddit.description)
在运行循环之前subreddit
对象将具有属性subreddit.subscribers
^{<但是,如果在调用subreddit.description
之前完成for循环,则不存在cd5>}属性
由于Praw
文档根本没有指定如何简单地读取订阅者,我想他们的文档中会缺少很多内容
重申一下,Praw
只是举例说明问题的实质:
找出给定对象的可用属性(和方法)的最佳方法是什么
据我所知,
dir
是在当前时刻对对象执行此操作的方法。从help(dir)
:我几乎可以肯定,鉴于Python的动态特性,不可能枚举所有可能属于实例的内容。它允许您随时向实例添加属性
为了进行说明,请考虑以下代码:
如您所见,标准Python类对实例中的内容没有限制。您随意添加(或删除)属性和方法,而
dir
无法预测这一点如果您正在设计自己的代码,并且希望停止此行为,则可以定义类变量^{} :
下面是该代码的稍微修改版本:
但我不会为我不是从头开始设计的代码那样做。如果删除某些库动态修改实例结构的功能,它们将无法工作
相关问题 更多 >
编程相关推荐