Python 中通过元类实现数据类型
参考Panda-Sandbox中实现数据类型
import abc
class Type(metaclass=abc.ABCMeta):
""" Base Class for Panda-Sandbox Type Definitions """
__doc__ = """
Must Implement this class for subtype to create new instance.
Initialise its with params:
:param default::默认值
:param allow_empty::可取空
@Must implement with below methods:
:method parse::转化
:method check::校验
"""
def __init__(self, default=None, allow_empty=False):
self.default = default
self.allow_empty = allow_empty
self._value = None
def __set__(self, instance, value):
if self.check(value):
self._value = value
else:
self._value = self.parse(value)
def __str__(self):
if not self._value:
return str(self.default)
return str(self._value)
@abc.abstractmethod
def parse(self, value):
""" parse a raw input value to correct type value and locate in the value range """
@abc.abstractmethod
def check(self, value):
""" check the type of a raw value whether we need this type in this instance """