Python“属性"和“属性"之间有什么区别?和“属性"?

Python“属性

问题描述:

我通常对属性"和属性"之间的区别感到困惑,并且找不到一个很好的资源来简明地详细说明这些区别.

I am generally confused about the difference between a "property" and an "attribute", and can't find a great resource to concisely detail the differences.

属性是一种特殊的属性.基本上,当Python遇到如下代码时:

Properties are a special kind of attribute. Basically, when Python encounters the following code:

spam = SomeObject()
print(spam.eggs)

它在spam中查找eggs,然后检查eggs是否有__get____set____delete__ 方法 — 如果是,则它是一个属性.如果它一个属性,它会调用__get__方法,而不是仅仅返回eggs对象(就像任何其他属性一样)因为我们正在进行查找)并返回该方法返回的任何内容.

it looks up eggs in spam, and then examines eggs to see if it has a __get__, __set__, or __delete__ method — if it does, it's a property. If it is a property, instead of just returning the eggs object (as it would for any other attribute) it will call the __get__ method (since we were doing lookup) and return whatever that method returns.

有关Python 的数据模型和描述符的更多信息.