Python的"__get * __"之间有什么区别?和"_del * __"方法? [英] What are the differences amongst Python's "__get*__" and "_del*__" methods?

查看:125
本文介绍了Python的"__get * __"之间有什么区别?和"_del * __"方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个月前我才刚开始学习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 Descriptors by Marty Alchin Part 1 and Part 2
  • SO question Understanding __get__ and __set__ and Python descriptors
  • google

可以定义的方法来自定义类实例的属性访问(使用,分配或删除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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆