實(shí)現(xiàn)了__set__(), __get__()或__delete__()的對(duì)象,且描述符屬性只能定義在類級(jí)別。
@property可利用描述符實(shí)現(xiàn)。(@classmethod, @staticmethod等也可以用描述符實(shí)現(xiàn))
利用描述符來進(jìn)行類型檢查。
<b>Python中屬性引用解析的執(zhí)行方式,優(yōu)先級(jí)鏈搜索屬性。</b>數(shù)據(jù)描述符(實(shí)現(xiàn)了__set__(), __get__())優(yōu)先級(jí)>實(shí)例變量>非數(shù)據(jù)描述符(只實(shí)現(xiàn)__get__())。在下例中實(shí)際給屬性賦值時(shí), u_0.name='test'等同于type(u_0).__dict__['name'].__set__(u_0, 'test'),取值,訪問屬性u_.name等同于type(u_0).__dict__['name'].__get__(u_0, type(u_0))
class Field(object):
_expected_type = type(None)
def __init__(self, name):
self.name = name
def __set__(self, instance, value):
if not isinstance(value, self._expected_type):
raise TypeError('excepted %s' % self._expected_type)
# setattr(instance, self.name, value)
instance.__dict__[self.name] = value
def __get__(self, instance, owner):
if not instance:
return self
# getattr(instance, self.name)
return instance.__dict__[self.name]
class StringField(Field):
_expected_type = str
class IntField(Field):
_expected_type = int
class User_0(object):
name = StringField('name')
age = IntField('age')
def __init__(self, name, age):
self.name = name
self.age = age
u_0 = User_0(name='JiangW', age=22)
u_0.name = 'test'
print(u_.age)
# TypeError: excepted <class 'int'>
# User_0(name='JiangW', age='22')
其他方式實(shí)現(xiàn)類型檢查。
利用函數(shù)和@property。property實(shí)際是一個(gè)描述符類,CheckType()方法返回的實(shí)際是一個(gè)<class 'property'>的對(duì)象, 該對(duì)象也是實(shí)現(xiàn)了__set__(), __get__()。
def CheckType(name, expected_type):
_name = name
@property
def res(self):
return getattr(self, _name)
@res.setter
def res(self, value):
if not isinstance(value, expected_type):
raise TypeError('excepted type %s' % excepted_type)
setattr(self, _name, value)
return res