class CheckString:
def __init__(self, variable_type):
self.variable_type = variable_type
def __set__(self, instance, value):
print('__set__:', value)
self.value = "error:類型錯誤"
if self.variable_type == 'str':
self.value = value if isinstance(value, str) else "error:類型錯誤"
def __get__(self, instance, owner):
print("__get__")
return self.value
pass
def __delete__(self, instance):
pass
class InfoModel:
name = CheckString(variable_type='str')
if __name__ == '__main__':
info = InfoModel()
info.name = "北門吹雪"
print(info.name)
經過另一個類來描敘類變量的屬性類型,這個是ORM實現的核心基礎python
給屬性賦值會調用 __set__方法,訪問屬性則會調用 __get__方法,則能夠獲取字段的對象和其值,刪除字段時候則調用 __delete__方法spa
北門吹雪: https://www.cnblogs.com/2bjiujiu/對象