Python 的“__get*__”和“__get*__”有什么区别?和“_del*__”方法?
我几个月前刚刚开始学习 Python,我试图理解不同的 __get*__ 方法之间的差异:
__get__
__getattr__
__getattribute__
__getitem___
以及它们的 __del*__ 等效项:
__del__
__delattr__
__delete__
__delitem__
什么是这些之间的区别?我什么时候应该使用其中一种而不是另一种?大多数 __get*__
方法都有 __set*__
等效项,但没有 __setattribute__
,这是否有特定原因?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以从文档索引轻松访问您列出的每种方法的文档。
无论如何,这可能是一个小小的扩展参考:
__get__
、__set__
和__del__
是描述符“简而言之,描述符是一种方法自定义引用模型上的属性时会发生的情况。” [官方文档链接]
它们得到了很好的解释,所以这里有一些参考:
__getattr__
,__getattribute__
、__setattr__
、__delattr__
可以定义这些方法来自定义属性访问的含义(使用、赋值或删除类实例的
x.name
)。 [官方文档链接]示例 1:
示例 2:
__getitem__
、__setitem__
、__delitem__
是以下方法: 可以定义为实现容器对象。 [官方文档链接]
示例:
我希望这足以让您有一个总体了解。
The documentation for every method that you listed is easly reachable from the documentation index .
Anyway this may be a little extended reference:
__get__
,__set__
and__del__
are descriptors"In a nutshell, a descriptor is a way to customize what happens when you reference an attribute on a model." [official doc link]
They are well explained around, so here there are some references:
__getattr__
,__getattribute__
,__setattr__
,__delattr__
Are methods that can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of
x.name
) for class instances. [official doc link]Example 1:
Example 2:
__getitem__
,__setitem__
,__delitem__
Are methods that can be defined to implement container objects. [official doc link]
Example:
I hope this is enough to give you a general idea.