gpt4 book ai didi

python - inspect.getmembers() vs __dict__.items() vs dir()

转载 作者:IT老高 更新时间:2023-10-28 22:19:15 25 4
gpt4 key购买 nike

谁能用足够的例子向我解释一下b/w有什么区别

>>> import inspect
>>> inspect.getmembers(1)

>>> type(1).__dict__.items()

>>> dir(1)  

除了它们显示的属性和方法的数量按此顺序递减。1 是整数(但它可以是任何类型。)


编辑

>>>obj.__class__.__name__  #gives the class name of object  
>>>dir(obj) #gives attributes & methods
>>>dir() #gives current scope/namespace
>>>obj.__dict__ #gives attributes

最佳答案

dir() 允许您通过定义 __dir__() 来自定义对象报告的属性。

从手册中,如果 __dir__() 没有定义:

If the object is a module object, the list contains the names of the module’s attributes.

If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

这也是 inspect.getmembers() 返回的内容,只不过它返回的是 (name, attribute) 的元组,而不仅仅是名称。

object.__dict__{key: attribute, key2: atrribute2} 等形式的字典。

object.__dict__.keys() 有其他两个所缺少的。

来自 inspect.getmembers() 上的文档:

getmembers() does not return metaclass attributes when the argument is a class (this behavior is inherited from the dir() function).

对于 int.__dict__.keys(),这是

['__setattr__', '__reduce_ex__', '__reduce__', '__class__', '__delattr__', '__subclasshook__', '__sizeof__', '__init__']

总结一下,dir()inspect.getmembers()基本相同,而__dict__是包含元类属性的完整命名空间.

关于python - inspect.getmembers() vs __dict__.items() vs dir(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6761106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com