Python的“ __get * __”和“ _del * __”方法有什么区别?

发布于 2021-01-29 15:10:41

我几个月前才刚刚开始学习Python,我试图了解不同__get*__方法之间的区别:

__get__
__getattr__
__getattribute__
__getitem___

及其__del*__等效项:

__del__
__delattr__
__delete__
__delitem__

这些之间有什么区别?我什么时候应该使用另一个?大多数__get*__方法都具有__set*__等效功能,但是没有特定的原因__setattribute__吗?

关注者
0
被浏览
100
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以从文档索引轻松找到列出的每种方法的文档

    无论如何,这可能是一个扩展的参考:

    __get____set__并且__del__是描述符

    简而言之,描述符是一种自定义当您引用模型上的属性时发生的情况的方法。”
    [官方文档链接]

    对其进行了很好的解释,因此这里有一些参考:

    __getattr____getattribute____setattr____delattr__

    可以定义以自定义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__

    可以定义以实现容器对象的方法。
    [官方文档链接]

    例:

    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
    

    我希望这足以给您一个总体思路。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看