不,原因与此相同:
>>> class Foo(object):
... bar = 'Foo attribute'
...
>>> f = Foo()
>>> f.bar
'Foo attribute'
>>> Foo.bar
'Foo attribute'
>>> f.bar = 'instance attribute'
>>> f.bar
'instance attribute'
>>> Foo.bar
'Foo attribute'
当您将属性分配给对象时,该对象的同名的类属性将被“黯然失色”.然而,在属性查找中,如果所讨论的对象没有定义所述属性,则将返回类1.
在Django中,ORM层使用这些类属性来生成转换为SQL查询和操作的机制(深层次的元类魔术在幕后).
编辑:回答你的问题 –
要理解,您需要了解一些关于Python的data model.基本上,类和对象都有命名空间.如果你偷看他们的特殊__dict__属性,这是很明显的:
>>> print Foo.__dict__
{'__dict__': , '__weakref__':
'__weakref__' of 'Foo' objects>, '__module__': '__main__', 'bar': 'Foo attribute
', '__doc__': None}
>>> f = Foo()
>>> print f.__dict__
{}
当对象f首次创建时,它有一个空的命名空间.当你做一个查找,f.bar,这个命名空间(真的,一个字典)被查找.由于没有发现’bar’属性,所以f的类Foo被查找.我们在那里找到’bar’:’Foo属性’.所以这将是什么回报:
>>> f.bar
'Foo attribute'
现在,当您为某个对象分配属性值,并且该属性名称在其命名空间中尚不存在时,将创建它:
>>> f.bar = 'instance attribute'
>>> print f.__dict__
{'bar': 'instance attribute'}
>>> f.bar
'instance attribute'
现在,你知道下一次f.bar是怎么回事! f .__ dict __ [‘bar’]存在,并在我们再看Foo的命名空间之前返回.
当然,如果您的意图是始终访问和操作类的属性而不是实例,则需要使用类的名称.
>>> Foo.bar
'Foo attribute'
>>> Foo.__dict__['bar']
'Foo attribute'