前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python学习笔记6.5-类中描述符的使用

python学习笔记6.5-类中描述符的使用

作者头像
锦小年
发布2018-01-02 14:23:14
5880
发布2018-01-02 14:23:14
举报
文章被收录于专栏:锦小年的博客锦小年的博客

描述符(Descriptor)就是以特殊方法get(), set(), delete()的形式实现了三个核心的属性访问操作(set,get,delete)的类。这些方法接受类实例作为输入来工作。之后,底层的实例字典会根据需要适当的进行调整。 要使用一个描述符,首先要创建一个描述符类,然后把描述符的实例放在类的定义中作为类变量来使用。事例如下:

代码语言:javascript
复制
#Descriptor attribute for an integer TYPE-checked attribute
class Integer:
    def __init__(self,name):
        self.name = name

    def __get__(self,instance,cls):
        if instance is None:
            return self
        else:
            return instance.__dict__[self.name]

    def __set__(self,instance,value):
        if not isinstance(value,int):
            raise TypeError('Expected an int')
        instance.__dict__[self.name] = value

    def __delete__(self,instance):
        del instance.__dict__[self.name]

class Point:
    x = Integer('x')  #must be a class variable
    y = Integer('y')
    def __init__(self,x,y):
        self.x = x
        self.y = y

p = Point(2,3)  
print(p.x)
print(p.y)

p.x = 5
print(p.x)
p.x = 'r'
print(p.x)

打印输出:
 File "D:/home/WX/test_descriptor.py", line 33, in <module>
2
3
5
Traceback (most recent call last):
    p.x = 'r'
  File "D:/home/WX/test_descriptor.py", line 14, in __set__
    raise TypeError('Expected an int')
TypeError: Expected an int

每一个描述符方法都会接受被操作的实例作为输入。要执行所请求的操作,底层的实例字典(即dict属性)会根据需要进行适当的调整。描述符的self.name属性会保存字典的键值,通过这些键可以找到储存在实例字典中的实例数据。(这就是python描述符运行机制,不好理解,但一定要多读去记住,很快就会理解)

对于大多数python类的特性,描述符都提供了底层的魔法,包括@classmethod、 @staticmethod、@property 甚至是slot()。

通过定义一个描述符,我们可以在很底层的情况下捕获关键的实例操作(get,set,delete),并且可以完全自定义这些操作行为。灵活运用操作符,会让程序变得更加简洁易懂。 关于操作符,我们必须有正确的理解,它们必须在类的层次上定义,不能根据实例来产生(很重要)。下面的代码无法工作:

代码语言:javascript
复制
class Point:
    def __init__(self,x,y):
        self.x = Integer('x')
        self.y = Integer('y')

另外,在我们的例子中看到,get()方法实现也复杂一些,因为实例变量和类变量是有区别的。如果以类变量的形式访问描述符,参数instance应该设为None。 这种情况下,标准的做法就是简单的返回描述符实例本身。 描述符常常作为一个组件出现在大型的编程框架中,其中还会涉及装饰器或者元类。正因为如此,对于描述符的使用可能隐藏很深,几乎看不到痕迹。例如:

代码语言:javascript
复制
#descriptor for a type_checked attribute
class Typed:
    def __init__(self,name,expected_type):
        self.name = name
        self.expected_type = expected_type

    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            return instance.__dict__[self.name]

    def __set__(self,instance,value):
        if not isinstance(value,self.expected_type):
            raise TypeError('Expected' + str(self.expected_type))
        instance.__dict__[self.name] = value

    def __delete__(self, instance):
        del instance.__dict__[self.name]

#Class decorator that applies it to selected attribute
def typeassert(**kwargs):
    def decorate(cls):
        for name,expected_type in kwargs.items():
            #Attach a typed descripor to the class
            setattr(cls,name,Typed(name,expected_type))
        return cls
    return decorate
#Example use
@typeassert(name=str, shares=int, price=float)
class Stock:
    def __init__(self,name,shares,price):
        self.name = name
        self.shares = shares
        self.price = price

a = Stock('libai',5,5.4)
a.name = 3

打印输出:
Traceback (most recent call last):
  File "D:/home/WX/test_descriptor.py", line 61, in <module>
    a.name = 3
  File "D:/home/WX/test_descriptor.py", line 38, in __set__
    raise TypeError('Expected' + str(self.expected_type))
TypeError: Expected<class 'str'>

最后,应该强调的是:如果只想访问某个特定的类中的一种属性,并且做一些自定义处理,那么最好不要编写描述符来实现。对于这样的任务,使用@property函数更加简单。针对于大量重用的代码的情况下,使用描述符更加有用(例如,我们需要在自己的代码中大量使用描述符提供的功能,或者将其作为库来使用)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档