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

2024-10-05 14:05:38 发布

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

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

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

不过,上面的方法是可行的,在调用某个方法之后,可能会添加一些可公开访问的属性

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

print(subreddit.description)

在运行循环之前subreddit对象将具有属性subreddit.subscribers^{<但是,如果在调用subreddit.description之前完成for循环,则不存在cd5>}属性

由于Praw文档根本没有指定如何简单地读取订阅者,我想他们的文档中会缺少很多内容

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

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


Tags: 对象实例方法in文档for属性dir
1条回答
网友
1楼 · 发布于 2024-10-05 14:05:38

据我所知,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无法预测这一点

如果您正在设计自己的代码,并且希望停止此行为,则可以定义类变量^{}

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

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'

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

相关问题 更多 >

    热门问题