其他分享
首页 > 其他分享> > 实现数据模型或类型系统

实现数据模型或类型系统

作者:互联网

想定义各种类型的数据结构,但是要对允许分配给某些属性的值实施约束。在此问题中,基本上要面对某些实例属性的设置进行检查或声明。 为此,需要基于每个属性自定义属性的设置,此时应该使用描述符。一般通过类及类的继承系统来实现,如下示例:

# Base class. Uses a descriptor to set a value
class Descriptor:
    def __init__(self, name=None, **opts):
        self.name = name
        for key, value in opts.items():
            setattr(self, key, value)
    
    def __set__(self, instance, value):
        instance.__dict__[self.name] = value


# Descriptor for enforcing types
class Typed(Descriptor):
    expected_type = type(None)

    def __set__(self, instance, value):
        if not isinstance(value, self.expected_type):
            raise TypeError('expected ' + str(self.expected_type))
        super().__set__(instance, value)


# Descriptor for enforcing values
class Unsigned(Descriptor):
    def __set__(self, instance, value):
        if value < 0:
            raise ValueError('Expected >= 0')
        super().__set__(instance, value)


class MaxSized(Descriptor):
    def __init__(self, name=None, **opts):
        if 'size' not in opts:
            raise TypeError('missing size option')
        super().__init__(name, **opts)

    def __set__(self, instance, value):
        if len(value) >= self.size:
            raise ValueError('size must be < ' + str(self.size))
        super().__set__(instance, value)


class Integer(Typed):
    expected_type = int


class UnsignedInteger(Integer, Unsigned):
    pass


class Float(Typed):
    expected_type = float


class UnsignedFloat(Float, Unsigned):
    pass


class String(Typed):
    expected_type = str


class SizedString(String, MaxSized):
    pass


class Stock:
    # Specify constraints
    name = SizedString('name', size=8)
    shares = UnsignedInteger('shares')
    price = UnsignedFloat('price')
    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price


>>> s = Stock('ACME', 50, 91.1) 
>>> s.name
'ACME'
>>> s.shares = 75
>>> s.shares = -10
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "example.py", line 17, in __set__
        super().__set__(instance, value) 
    File "example.py", line 23, in __set__
        raise ValueError('Expected >= 0') 
ValueError: Expected >= 0
>>> s.price = 'a lot'
Traceback (most recent call last):
    File "<stdin>", line 1, in <module> 
    File "example.py", line 16, in __set__
        raise TypeError('expected ' + str(self.expected_type)) 
TypeError: expected <class 'float'>
>>> s.name = 'ABRACADABRA'
Traceback (most recent call last):
    File "<stdin>", line 1, in <module> 
    File "example.py", line 17, in __set__
        super().__set__(instance, value) 
    File "example.py", line 35, in __set__
        raise ValueError('size must be < ' + str(self.size)) 
ValueError: size must be < 8
>>>

另一种实现方式是使用类装饰器,如下:

def check_attributes(**kwargs):
    def decorate(cls):
        for key, value in kwargs.items():
            if isinstance(value, Descriptor):
                value.name = key
                setattr(cls, key, value)
            else:
                setattr(cls, key, value(key))
        return cls
    return decorate


# Example
@check_attributes(name=SizedString(size=8), shares=UnsignedInteger,
price=UnsignedFloat)
class Stock:
    def __Init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price

第三种方式是使用元类,如下:

# A metaclass that applies checking
class checkedmeta(type):
    def __new__(cls, clsname, bases, methods):
        # Attach attribute names to the descriptors
        for key, value in methods.items():
            if isinstance(value, Descriptor):
                value.name = key
        return type(cls, clsname, bases, methods)


# Example
class Stock(metaclass=checkedmeta):
    name = SizedString(size=8)
    shares = UnsignedInteger() 
    price = UnsignedFloat()
    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price

本篇博文包含Python编程中的很多高级技巧和语言系统,如描述符,mixin类,super()的多重继承,类装饰器,元类等。这也是Python进阶中必须跨过的门槛。
· 首先,在Descriptor类中引入了__get__, __set__, __delete__等实现描述符协议的类方法。这在包含该类示例的类属性中使用属性访问时使用。

最后:在所有方法中,类装饰器解决方案都可以提供最大的灵活性和完整性。 一方面,它不依赖任何高级机制,例如元类。 其次,装饰器是可以很容易地根据需要从类定义中添加或删除。 例如,在装饰器中,可能有一个选项可以完全省略所添加的检查。 这些可能使检查成为可以根据需求打开或关闭(例如debug还是production模式)。

标签:__,set,name,self,系统,value,shares,类型,数据模型
来源: https://www.cnblogs.com/jeffrey-yang/p/12117174.html