Python“属性"和“属性"之间有什么区别?和“属性"? [英] What's the difference between a Python "property" and "attribute"?
问题描述
我通常对属性"和属性"之间的区别感到困惑,并且找不到一个很好的资源来简明地详细说明这些区别.
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 的数据模型和描述符的更多信息.
这篇关于Python“属性"和“属性"之间有什么区别?和“属性"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!