python进阶--描述器和ORM模型

描述器和ORM模型

描述器

描述器定义:对象中定义了__get__()__set__()__delete__()方法中的任意一个,这个对象就是一个描述器

描述器作用:描述器功能强大,应用广泛,它可以控制我们访问属性、方法的行为,是@property、super、静态方法、类方法、甚至属性、实例背后的实现机制,是一种比较底层的设计

描述器官方文档:https://docs.python.org/zh-cn/3/howto/descriptor.html

# __get__() 、__set__() 、 __delete__()方法
class Filed():
    def __get__(self,instance,owner):
        print("访问属性的时候被触发")
        print(instance)       #  instance是属性访问的实例
        print(owner)          #   owner始终是属主
        print(self.value)
        return self.value

    def __set__(self,instance,value):
        print("设置set方法被触发")
        self.value = value

    def __delete__(self,instance):
        print("删除属性的时候被触发")
        self.value = None

class A:
    name = Filed()

a = A()
a.name = 'lili'

a.name
del a.name

>
设置set方法被触发
访问属性的时候被触发
<__main__.A object at 0x7fb3076ba0a0>
<class '__main__.A'>
lili
删除属性的时候被触发
# 描述器
import os

class DirectorySize:

    def __get__(self, obj, objtype=None):
        return len(os.listdir(obj.dirname))

class Directory:

    size = DirectorySize()              # Descriptor instance

    def __init__(self, dirname):
        self.dirname = dirname          # Regular instance attribute

·
a = Directory(r'/Users/whtest/Desktop/Hrunner/HrunDemo')
print(a.size)

b = Directory(r'/Users/whtest/Desktop/Hrunner')
print(b.size)

ORM

ORM定义:Object/Relational Mapping,通过使用描述对象和数据库之间映射的元数据,将程序中的对象与关系数据库相互映射的技术
ORM作用:负责实体域对象的持久化,封装数据库访问细节。

ORM把数据库映射成对象

数据库的表(table) --> 类(class)
记录(record,行数据)--> 对象(object)
字段(field)--> 对象的属性(attribute)

参考文档

http://www.ruanyifeng.com/blog/2019/02/orm-tutorial.html
https://www.cnblogs.com/best/p/9711215.html

描述器实现ORM描述

class Filed():
    def __init__(self, length):
        self.max_length = length

    def __get__(self,instance,owner):
        return self.value

    def __set__(self,instance,value):
        if isinstance(value, str):
            if len(value) <= self.max_length:
                self.value = value
            else:
                raise ValueError('字符串长度不超过{}字符'.format(self.max_length))
        else:
            raise TypeError('请输入字符串类型')

    def __delete__(self,instance):
        self.value = None

class A:
    name = Filed(10)

a = A()
a.name = 'lililililil'

>
ValueError: 字符串长度不超过10字符

猜你喜欢

转载自blog.csdn.net/qq_25672165/article/details/111290235