iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python基础详解之描述符
  • 404
分享到

Python基础详解之描述符

2024-04-02 19:04:59 404人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录一、描述符定义二、描述符的种类和优先级三、描述符的应用四、描述符 + 类装饰器  (给 Person类添加类属性)五、利用描述符自定义 @property六、prope

一、描述符定义

描述符是一种类,我们把实现了__get__()、__set__()和__delete__()中的其中任意一种方法的类称之为描述符。

描述符的作用是用来代理一个类的属性,需要注意的是描述符不能定义在被使用类的构造函数中,只能定义为类的属性,它只属于类的,不属于实例,我们可以通过查看实例和类的字典来确认这一点。

描述符是实现大部分python类特性中最底层的数据结构的实现手段,我们常使用的@claSSMethod、@staticmethd、@property、甚至是__slots__等属性都是通过描述符来实现的。它是很多高级库和框架的重要工具之一,是使用到装饰器或者元类的大型框架中的一个非常重要组件。

如下示例一个描述符及引用描述符类的代码:


class Descriptors:
 
    def __init__(self, key, value_type):
        self.key = key
        self.value_type = value_type
 
    def __get__(self, instance, owner):
        print("===> 执行Descriptors的 get")
        return instance.__dict__[self.key]
 
    def __set__(self, instance, value):
        print("===> 执行Descriptors的 set")
        if not isinstance(value, self.value_type):
            raise TypeError("参数%s必须为%s" % (self.key, self.value_type))
        instance.__dict__[self.key] = value
 
    def __delete__(self, instance):
        print("===>  执行Descriptors的delete")
        instance.__dict__.pop(self.key)
 
 
class Person:
    name = Descriptors("name", str)
    age = Descriptors("age", int)
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
 
person = Person("xu", 15)
print(person.__dict__)
person.name
person.name = "xu-1"
print(person.__dict__)
# 结果:
#     ===> 执行Descriptors的 set
#     ===> 执行Descriptors的 set
#     {'name': 'xu', 'age': 15}
#     ===> 执行Descriptors的 get
#     ===> 执行Descriptors的 set
#     {'name': 'xu-1', 'age': 15}

其中,Descriptors类就是一个描述符,Person是使用描述符的类。

类的__dict__属性是类的一个内置属性,类的静态函数、类函数、普通函数、全局变量以及一些内置的属性都是放在类__dict__里。

在输出描述符的变量时,会调用描述符中的__get__方法,在设置描述符变量时,会调用描述符中的__set__方法。

二、描述符的种类和优先级

描述符分为数据描述符和非数据描述符。

至少实现了内置__set__()和__get__()方法的描述符称为数据描述符;实现了除__set__()以外的方法的描述符称为非数据描述符。

描述符的优先级的高低顺序:类属性 > 数据描述符 > 实例属性 > 非数据描述符 > 找不到的属性触发__getattr__()。

在上述“描述符定义”章节的例子中,实例person的属性优先级低于数据描述符Descriptors,所以在赋值或获取值过程中,均调用了描述符的方法。


class Descriptors:
    def __get__(self, instance, owner):
        print("===> 执行 Descriptors get")
 
    def __set__(self, instance, value):
        print("===> 执行 Descriptors set")
 
    def __delete__(self, instance):
        print("===> 执行 Descriptors delete")
 
 
class University:
    name = Descriptors()
 
    def __init__(self, name):
        self.name = name

类属性 > 数据描述符


# 类属性 > 数据描述符
# 在调用类属性时,原来字典中的数据描述法被覆盖为 XX-XX
print(University.__dict__)  # {..., 'name': <__main__.Descriptors object at 0x7ff8c0eda278>,}
 
University.name = "XX-XX"
print(University.__dict__)  # {..., 'name': 'XX-XX',}

数据描述符 > 实例属性


# 数据描述符 > 实例属性
# 调用时会现在实例里面找,找不到name属性,到类里面找,在类的字典里面找到 'name': <__main__.Descriptors object at 0x7fce16180a58>
# 初始化时调用 Descriptors 的 __set__; un.name 调用  __get__
print(University.__dict__)
un = University("xx-xx")
un.name
# 结果:
#     {..., 'name': <__main__.Descriptors object at 0x7ff8c0eda278>,}
#     ===> 执行 Descriptors set
#     ===> 执行 Descriptors get

下面是测试 实例属性、 非数据描述符、__getattr__ 使用代码


class Descriptors:
    def __get__(self, instance, owner):
        print("===>2 执行 Descriptors get")
 
 
class University:
    name = Descriptors()
 
    def __init__(self, name):
        self.name = name
 
    def __getattr__(self, item):
        print("---> 查找 item = {}".fORMat(item))

实例属性 > 非数据描述符


# 实例属性 > 非数据描述符
# 在创建实例的时候,会在属性字典中添加 name,后面调用 un2.name 访问,都是访问实例字典中的 name
un2 = University("xu2")
print(un2.name)  # xu    并没有调用到  Descriptors 的 __get__
print(un2.__dict__)  # {'name': 'xu2'}
un2.name = "xu-2"
print(un2.__dict__)  # {'name': 'xu-2'}

非数据描述符 > 找不到的属性触发__getattr__


# 非数据描述符 > 找不到的属性触发__getattr__
# 找不到 name1 使用 __getattr__
un3 = University("xu3")
print(un3.name1)  # ---> 查找 item = name1

三、描述符的应用

使用描述符检验数据类型


class Typed:
    def __init__(self, key, type):
        self.key = key
        self.type = type
 
    def __get__(self, instance, owner):
        print("---> get 方法")
        # print("instance = {}, owner = {}".format(instance, owner))
        return instance.__dict__[self.key]
 
    def __set__(self, instance, value):
        print("---> set 方法")
        # print("instance = {}, value = {}".format(instance, value))
        if not isinstance(value, self.type):
            # print("设置name的值不是字符串: type = {}".format(type(value)))
            # return
            raise TypeError("设置{}的值不是{},当前传入数据的类型是{}".format(self.key, self.type, type(value)))
        instance.__dict__[self.key] = value
 
    def __delete__(self, instance):
        print("---> delete 方法")
        # print("instance = {}".format(instance))
        instance.__dict__.pop(self.key)
 
 
class Person:
    name = Typed("name", str)
    age = Typed("age", int)
 
    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary
 
 
p1 = Person("xu", 99, 100.0)
print(p1.__dict__)
p1.name = "XU1"
print(p1.__dict__)
del p1.name
print(p1.__dict__)
# 结果:
#     ---> set 方法
#     ---> set 方法
#     {'name': 'xu', 'age': 99, 'salary': 100.0}
#     ---> set 方法
#     {'name': 'XU1', 'age': 99, 'salary': 100.0}
#     ---> delete 方法
#     {'age': 99, 'salary': 100.0}

四、描述符 + 类装饰器  (给 Person类添加类属性)

类装饰器,道理和函数装饰器一样


def Typed(**kwargs):
    def deco(obj):
        for k, v in kwargs.items():
            setattr(obj, k, v)
        return obj
    return deco
 
 
@Typed(x=1, y=2)  # 1、Typed(x=1, y=2) ==> deco   2、@deco ==> Foo = deco(Foo)
class Foo:
    pass
 
 
# 通过类装饰器给类添加属性
print(Foo.__dict__)  # {......, 'x': 1, 'y': 2}
print(Foo.x)

使用描述符和类装饰器给 Person类添加类属性


"""
描述符 + 类装饰器
"""
class Typed:
    def __init__(self, key, type):
        self.key = key
        self.type = type
 
    def __get__(self, instance, owner):
        print("---> get 方法")
        # print("instance = {}, owner = {}".format(instance, owner))
        return instance.__dict__[self.key]
 
    def __set__(self, instance, value):
        print("---> set 方法")
        # print("instance = {}, value = {}".format(instance, value))
        if not isinstance(value, self.type):
            # print("设置name的值不是字符串: type = {}".format(type(value)))
            # return
            raise TypeError("设置{}的值不是{},当前传入数据的类型是{}".format(self.key, self.type, type(value)))
        instance.__dict__[self.key] = value
 
    def __delete__(self, instance):
        print("---> delete 方法")
        # print("instance = {}".format(instance))
        instance.__dict__.pop(self.key)
 
 
def deco(**kwargs):
    def wrapper(obj):
        for k, v in kwargs.items():
            setattr(obj, k, Typed(k, v))
        return obj
    return wrapper
 
 
@deco(name=str, age=int)
class Person:
    # name = Typed("name", str)
    # age = Typed("age", int)
 
    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary
 
 
p1 = Person("xu", 99, 100.0)
print(Person.__dict__)
print(p1.__dict__)
p1.name = "XU1"
print(p1.__dict__)
del p1.name
print(p1.__dict__)
# 结果:
#     ---> set 方法
#     ---> set 方法
#     {..., 'name': <__main__.Typed object at 0x7f3D79729dd8>, 'age': <__main__.Typed object at 0x7f3d79729e48>}
#     {'name': 'xu', 'age': 99, 'salary': 100.0}
#     ---> set 方法
#     {'name': 'XU1', 'age': 99, 'salary': 100.0}
#     ---> delete 方法
#     {'age': 99, 'salary': 100.0}

五、利用描述符自定义 @property


class Lazyproperty:
    def __init__(self, func):
        self.func = func
 
    def __get__(self, instance, owner):
        print("===> Lazypropertt.__get__ 参数: instance = {}, owner = {}".format(instance, owner))
        if instance is None:
            return self
        res = self.func(instance)
        setattr(instance, self.func.__name__, res)
        return self.func(instance)
 
    # def __set__(self, instance, value):
    #     pass
 
 
class Room:
 
    def __init__(self, name, width, height):
        self.name = name
        self.width = width
        self.height = height
 
    # @property  # area=property(area)
    @Lazyproperty  # # area=Lazyproperty(area)
    def area(self):
        return self.width * self.height
 
#  @property 测试代码
# r = Room("房间", 2, 3)
# print(Room.__dict__)  # {..., 'area': <property object at 0x7f8b42de5ea8>,}
# print(r.area)  # 6
 
# r2 = Room("房间2", 2, 3)
# print(r2.__dict__)  # {'name': '房间2', 'width': 2, 'height': 3}
# print(r2.area)
 
# print(Room.area)  # <__main__.Lazyproperty object at 0x7faabd589a58>
 
r3 = Room("房间3", 2, 3)
print(r3.area)
print(r3.area)
# 结果(只计算一次):
#     ===> Lazypropertt.__get__ 参数: instance = <__main__.Room object at 0x7fd98e3757b8>, owner = <class '__main__.Room'>
#     6
#     6

六、property 补充


class Foo:
 
    @property
    def A(self):
        print("===> get A")
 
    @A.setter
    def A(self, val):
        print("===> set A, val = {}".format(val))
 
    @A.deleter
    def A(self):
        print("===> del A")
 
 
f = Foo()
f.A         # ===> get A
f.A = "a"   # ===> set A, val = a
del f.A     # ===> del A
 
 
 
class Foo:
 
    def get_A(self):
        print("===> get_A")
 
    def set_A(self, val):
        print("===> set_A, val = {}".format(val))
 
    def del_A(self):
        print("===> del_A")
 
    A = property(get_A, set_A, del_A)
 
 
f = Foo()
f.A         # ===> get_A
f.A = "a"   # ===> set_A, val = a
del f.A     # ===> del_A

到此这篇关于Python基础详解之描述符的文章就介绍到这了,更多相关Python描述符内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python基础详解之描述符

本文链接: https://www.lsjlt.com/news/124859.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python基础详解之描述符
    目录一、描述符定义二、描述符的种类和优先级三、描述符的应用四、描述符 + 类装饰器  (给 Person类添加类属性)五、利用描述符自定义 @property六、prope...
    99+
    2024-04-02
  • 详解Python魔法方法之描述符类
    描述符类要求: 描述符就是将某种特殊类型的类的实例指派给另一个类的属性 至少要实现以下的一个方法: •__get__(self, instance, owner) ...
    99+
    2024-04-02
  • Python的描述符
    1、描述符的定义   描述符是与特定属性互相绑定的一种协议,通过方法被触发修改属性,这些方法包括__get__(),__set__(),__delete__().将这些方法定义在类中,即可实现描述符 2、属性与__dict__   Pyt...
    99+
    2023-01-30
    Python
  • 详解Python描述符的工作原理
    目录一、前言二、什么是描述符?三、描述符协议四、描述符的工作原理五、数据描述符和非数据描述符六、描述符的使用场景七、function与method八、property/staticm...
    99+
    2024-04-02
  • 详解Android文件描述符
    介绍文件描述符的概念以及工作原理,并通过源码了解 Android 中常见的 FD 泄漏。 一、什么是文件描述符? 文件描述符是在 Linux 文件系统的被使用,由于Android基 ...
    99+
    2024-04-02
  • Python基础之字符串格式化详解
    目录一、前言二、百分号2.1 通过位置传参2.2 通过关键字传参三、 format 方式3.1 参数数据类型3.2 传参的方式3.3 格式化的其他配置参数3.4 格式化时间一、前言 ...
    99+
    2024-04-02
  • Python编程基础之运算符重载详解
    目录学习目标一、运算符重载(一)概述(二)加法运算重载符1、概述2、案例演示总结学习目标 1.掌握运算符重载 2.会定制对象字符串的形式 一、运算符重载 (一)概述 运算符重载是通过...
    99+
    2024-04-02
  • Python描述符的使用
      前言 作为一位python的使用者,你可能使用python有一段时间了,但是对于python中的描述符却未必使用过,接下来是对描述符使用的介绍 场景介绍 为了引入描述符的使用,我们先设计一个非常简单的类: class Produ...
    99+
    2023-01-30
    Python
  • Python描述符怎么用
    这篇文章主要介绍“Python描述符怎么用”,在日常操作中,相信很多人在Python描述符怎么用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python描述符怎么用”的疑惑有所帮助!接下来,请跟着小编一起来...
    99+
    2023-06-17
  • python基础概述
    1、python简介 python诞生于1989年,创始人 吉多·范罗苏姆(Guido van Rossum)。python是一种 C和shell 之间,功能全面,易学易用,可拓展的语言。 如下是最新的TIOBE排行榜(https://ww...
    99+
    2023-01-31
    基础 python
  • python高级之描述器
    描述器用到的方法    用到3个魔术方法: __get__()、__set__()、__delete__()     方法使用格式:         obj.__get__(self, instance, owner)      ...
    99+
    2023-01-31
    高级 python
  • Python机器学习之基础概述
    目录一、基础概述二、算法分类三、研究内容一、基础概述 机器学习(Machine Learing)是一门多领域交叉学科,涉及概率论、统计学、逼近论、凸分析、算法复杂度理论等多...
    99+
    2024-04-02
  • Python基础——概述
      Jupyter Notebook是在浏览器中运行的。 地址栏输入http://localhost:8888后直接进入工作文件夹,显示文件夹中的内容。 右上角选择New——Python 3,新建Python代码。在文件夹中也可以找...
    99+
    2023-01-30
    基础 Python
  • Python中描述符有哪些
    这期内容当中小编将会给大家带来有关Python中描述符有哪些,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。python可以做什么Python是一种编程语言,内置了许多有效的工具,Python几乎无所不能,...
    99+
    2023-06-14
  • Python基础之模块详解
    目录一、模块1、模块的四种形式2、为什么要用模块?二、如何用模块1、import 模块名导入重命名:smt变量指向span模块的名称空间导入多个模块2、from 模块名 import...
    99+
    2024-04-02
  • Python基础之元类详解
    1.python 中一切皆是对象,类本身也是一个对象,当使用关键字 class 的时候,python 解释器在加载 class 的时候会创建一个对象(这里的对象指的是类而非类的实例)...
    99+
    2024-04-02
  • Python基础之进程详解
    目录一、前言二、基本用法三、创建单个进程四、创建多个进程五、进程池六、锁七、进程间通信八、信号量九、数据共享十、总结一、前言 进程,一个新鲜的字眼,可能有些人并不了解,它是系统某个运...
    99+
    2024-04-02
  • Python中有哪些描述符
    这篇文章将为大家详细讲解有关Python中有哪些描述符,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。python可以做什么Python是一种编程语言,内置了许多有效的工具,Python几乎无...
    99+
    2023-06-14
  • python基础字符串str详解
    目录字符串str:编码:ord(字符串)和chr(整数):字符串字面值:字符串通用操作字符串str: 定义:是由一系列字符组成的不可变序列容器,储存的事字符的编码值 编码:...
    99+
    2024-04-02
  • Python基础之字符串
    初识字符串 字符串的认识 首先,我们先认识下什么是字符串: # 定义字符串 t_str1 = "Hello World" t_str2 = "asdfghh" print(t_str1) # Hello World print(t_s...
    99+
    2023-01-31
    字符串 基础 Python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作