Python advanced-descriptor and ORM model

Descriptor and ORM model

Descriptor

描述器定义: Object defines __get__(), __set__(), __delete__()any of a method, the object is a descriptor

描述器作用: Descriptor is powerful and widely used. It can control the behavior of accessing properties and methods. It is the realization mechanism behind @property, super, static methods, class methods, and even properties and instances. It is a relatively low-level design

描述器官方文档: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)

SNAKE

ORM定义: Object/Relational Mapping, a technology that maps objects in a program to relational databases by using metadata describing the mapping between objects and databases
ORM作用: responsible for the persistence of entity domain objects and encapsulating database access details.

ORM maps the database to objects

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

Reference documents

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

Descriptor implements ORM description

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字符

Guess you like

Origin blog.csdn.net/qq_25672165/article/details/111290235