python中dir和__dict__之间的最大区别是什么 [英] what's the biggest difference between dir and __dict__ in python
问题描述
class C(object):
def f(self):
print self.__dict__
print dir(self)
c = C()
c.f()
输出:
{}
['__class__', '__delattr__','f',....]
为什么自我中没有'f'.__dict__
why there is not a 'f' in self.__dict__
推荐答案
dir()
除了查找__dict__
以外,还可以做更多的事情.
首先,dir()
是一种API方法,它知道如何使用__dict__
之类的属性来查找对象的属性.
dir()
does much more than look up __dict__
First of all, dir()
is a API method that knows how to use attributes like __dict__
to look up attributes of an object.
尽管并非所有对象都具有__dict__
属性.例如,如果要向自定义类添加 __slots__
属性,该类将没有__dict__
属性,但是dir()
仍然可以列出这些实例上的可用属性:
Not all objects have a __dict__
attribute though. For example, if you were to add a __slots__
attribute to your custom class, instances of that class won't have a __dict__
attribute, yet dir()
can still list the available attributes on those instances:
>>> class Foo(object):
... __slots__ = ('bar',)
... bar = 'spam'
...
>>> Foo().__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__dict__'
>>> dir(Foo())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'bar']
同样适用于许多内置类型. list
没有__dict__
属性,但是您仍然可以使用dir()
列出所有属性:
The same applies to many built-in types; list
s do not have a __dict__
attribute, but you can still list all the attributes using dir()
:
>>> [].__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__dict__'
>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
dir()
对实例有什么作用
Python实例具有自己的__dict__
,但它们的类也是如此:
What dir()
does with instances
Python instances have their own __dict__
, but so does their class:
>>> class Foo(object):
... bar = 'spam'
...
>>> Foo().__dict__
{}
>>> Foo.__dict__.items()
[('__dict__', <attribute '__dict__' of 'Foo' objects>), ('__weakref__', <attribute '__weakref__' of 'Foo' objects>), ('__module__', '__main__'), ('bar', 'spam'), ('__doc__', None)]
dir()
方法同时使用和这两个__dict__
属性,和 object
上的一个,以创建实例上可用属性的完整列表,班级,以及班级的所有祖先.
The dir()
method uses both these __dict__
attributes, and the one on object
to create a complete list of available attributes on the instance, the class, and on all ancestors of the class.
在类上设置属性时,实例也可以看到以下内容:
When you set attributes on a class, instances see these too:
>>> f = Foo()
>>> f.ham
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'ham'
>>> Foo.ham = 'eggs'
>>> f.ham
'eggs'
因为该属性已添加到类__dict__
:
because the attribute is added to the class __dict__
:
>>> Foo.__dict__['ham']
'eggs'
>>> f.__dict__
{}
请注意如何将实例__dict__
保留为空.在Python对象上进行属性查找遵循对象的层次结构,从实例到类型,再到父类,以搜索属性.
Note how the instance __dict__
is left empty. Attribute lookup on Python objects follows the hierarchy of objects from instance to type to parent classes to search for attributes.
仅当直接在实例上设置属性时,您会看到实例__dict__
中反映的属性,而类__dict__
保持不变:
Only when you set attributes directly on the instance, will you see the attribute reflected in the __dict__
of the instance, while the class __dict__
is left unchanged:
>>> f.stack = 'overflow'
>>> f.__dict__
{'stack': 'overflow'}
>>> 'stack' in Foo.__dict__
False
TLDR;或摘要
dir()
不仅会查找对象的__dict__
(有时甚至不存在),还会使用对象的遗产(其类或类型,以及该类或类的任何超类或父类)类型)为您提供所有可用属性的完整图片.
TLDR; or the summary
dir()
doesn't just look up an object's __dict__
(which sometimes doesn't even exist), it will use the object's heritage (its class or type, and any superclasses, or parents, of that class or type) to give you a complete picture of all available attributes.
实例__dict__
只是该实例上的本地"属性集,并不包含该实例上可用的每个属性.相反,您还需要查看类和类的继承树.
An instance __dict__
is just the 'local' set of attributes on that instance, and does not contain every attribute available on the instance. Instead, you need to look at the class and the class's inheritance tree too.
这篇关于python中dir和__dict__之间的最大区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!