Python的"__get * __"之间有什么区别?和"_del * __"方法? [英] What are the differences amongst Python's "__get*__" and "_del*__" methods?
问题描述
几个月前我才刚开始学习Python,我试图了解不同的__get*__
方法之间的区别:
I just started learning Python a few months ago, and I'm trying to understand the differences between the different __get*__
methods:
__get__
__getattr__
__getattribute__
__getitem___
及其等效的__del*__
:
__del__
__delattr__
__delete__
__delitem__
这些之间有什么区别?我什么时候应该在另一个上使用?为什么大多数__get*__
方法具有__set*__
等价物但没有__setattribute__
呢?
What are the differences between these? When should I use one over the other? Is there a specific reason why most of the __get*__
methods have __set*__
equivalents, but there is no __setattribute__
?
推荐答案
您可以从无论如何,这可能是一个扩展参考:
Anyway this may be a little extended reference:
简而言之,描述符是一种自定义在引用模型上的属性时发生的情况的方法." 它们的周围都有很好的解释,因此这里有一些参考文献:
They are well explained around, so here there are some references:
- Python描述符,作者:Marty Alchin 第1部分和第2部分
- SO问题了解__get__和__set__以及Python描述符
- Python Descriptors by Marty Alchin Part 1 and Part 2
- SO question Understanding __get__ and __set__ and Python descriptors
可以定义的方法来自定义类实例的属性访问(使用,分配或删除x.name
)的含义. 示例1:
class Foo:
def __init__(self):
self.x = 10
def __getattr__(self, name):
return name
f = Foo()
f.x # -> 10
f.bar # -> 'bar'
示例2:
class Foo:
def __init__(self):
self.x = 10
def __getattr__(self,name):
return name
def __getattribute__(self, name):
if name == 'bar':
raise AttributeError
return 'getattribute'
f = Foo()
f.x # -> 'getattribute'
f.baz # -> 'getattribute'
f.bar # -> 'bar'
__getitem__
,__setitem__
,__delitem__
可以定义实现容器对象的方法. [官方文档链接]
__getitem__
, __setitem__
, __delitem__
Are methods that can be defined to implement container objects. [official doc link]
示例:
class MyColors:
def __init__(self):
self._colors = {'yellow': 1, 'red': 2, 'blue': 3}
def __getitem__(self, name):
return self._colors.get(name, 100)
colors = MyColors()
colors['yellow'] # -> 1
colors['brown'] # -> 100
我希望这足以给您一个大致的想法.
I hope this is enough to give you a general idea.
这篇关于Python的"__get * __"之间有什么区别?和"_del * __"方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!