inspect.getmembers()vs __dict __.items()vs dir() [英] inspect.getmembers() vs __dict__.items() vs dir()

查看:122
本文介绍了inspect.getmembers()vs __dict __.items()vs dir()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以通过充分的例子向我解释一下黑白之间的区别

Can anybody explain to me with adequate examples whats the difference b/w

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

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

>>> dir(1)  

区别在于它们显示的属性&的数量减少了方法的顺序. 1是整数(但可以是任何类型.)

except that they show an decreasing no.s of attributes & methods in that order. 1 is integer (but it can be of any type.)

编辑

>>>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() allows you to customize what attributes your object reports, by defining __dir__().

根据手册,如果未定义__dir__():

From the manual, if __dir__() is not defined:

如果对象是模块对象,则列表包含模块属性的名称.

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)的元组而不只是名称.

This is also what inspect.getmembers() returns, except it returns tuples of (name, attribute) instead of just the names.

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

object.__dict__.keys()缺少其他两个.

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

当参数为类时,

getmembers()不会返回元类属性(此行为是从dir()函数继承的.)

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__是包括元类属性的完整命名空间.

To summarize, dir() and inspect.getmembers() are basically the same, while __dict__ is the complete namespace including metaclass attributes.

这篇关于inspect.getmembers()vs __dict __.items()vs dir()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆