首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python dir(dict) vs dir(dict.__class__)

Python dir(dict) vs dir(dict.__class__)
EN

Stack Overflow用户
提问于 2012-03-14 06:26:36
回答 2查看 2.2K关注 0票数 2

dir(x)dir(x.__class__)有什么区别?后者返回不同的属性列表,但与前者重叠。

例如,SQLAlchemy的sqlalchemy.create_engine()函数创建一个新的Engine实例。当我调用dir(engine) (假设engine是指向适当实例的变量)时,我会返回以下列表:

代码语言:javascript
复制
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', '_connection_cls', '_echo',
'_execute_clauseelement', '_execute_compiled', '_execute_default',
'_execution_options', '_has_events', '_run_visitor', '_should_log_debug',
'_should_log_info', 'connect', 'contextual_connect', 'create', 'dialect',
'dispatch', 'dispose', 'driver', 'drop', 'echo', 'engine', 'execute', 'func',
'has_table', 'logger', 'logging_name', 'name', 'pool', 'raw_connection',
'reflecttable', 'run_callable', 'scalar', 'table_names', 'text', 'transaction',
'update_execution_options', 'url']

调用dir(engine.__class__)会导致以下结果:

代码语言:javascript
复制
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', '_connection_cls',
'_execute_clauseelement', '_execute_compiled', '_execute_default',
'_execution_options', '_has_events', '_run_visitor', '_should_log_debug',
'_should_log_info', 'connect', 'contextual_connect', 'create', 'dispatch',
'dispose', 'driver', 'drop', 'echo', 'execute', 'func', 'has_table',
'logging_name', 'name', 'raw_connection', 'reflecttable', 'run_callable',
'scalar', 'table_names', 'text', 'transaction', 'update_execution_options']

这两个结果之间有重叠,但也有差异,我在解释差异及其原因的文档中没有找到任何特别有用的东西。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-14 06:29:41

粗略地说,dir(instance)列出了实例属性、类属性和所有基类的属性。dir(instance.__class__)只列出类的属性,所有基类的属性。

在使用dir()时,需要记住的重要一点是来自documentation的以下说明

因为dir()主要是为了方便在交互式提示符下使用而提供的,所以它试图提供一组有趣的名称,而不是提供一组严格或一致定义的名称,并且它的详细行为可能会因版本而异。例如,当参数是类时,元类属性不在结果列表中。

票数 6
EN

Stack Overflow用户

发布于 2012-03-14 06:29:51

区别应该是不言而喻的:在一种情况下,您请求实例的dir(),而在另一种情况下,您请求用作其模板的类的dir()。通过在__init__()方法中创建实例,实例可能具有不在类中的属性。

代码语言:javascript
复制
class Foo(object):
    def __init__(self):
        self.answer = 42

f = Foo()
set(dir(f)) - set(dir(Foo))
>>> set(['answer'])

实例属性用于存储特定于某个实例的数据。类属性存储类的所有实例共享的数据,有时也存储类本身使用的数据。方法是一种特殊情况,因为它们实际上存储在两个地方(它们是在类上定义的,但稍后会绑定到每个实例)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9693158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档