# 定义一个人的类,控制一下对实例属性的类型限定
# 实例化对象的时候,对参数进行一个数据类型的限定
class People:
def __init__(self,name):
= name
sq = People("sq")
error = People(123)
print(sq.__dict__)
print(error.__dict__)
C:\Users\python_hui\Anaconda3\python.exe G:/test/a/描述符实例/1.py
{‘name’: ‘sq’}
{‘name’: 123}
Process finished with exit code 0
需求,实例化时限定数据型》明确在set中各个参数是什么
结论
》描述符中的set 方法中 instance 就是实例对象本身, value 就是要给被代理的属性所赋的值
会出错的情况 完结-完整的代码class Manage:
"""数据描述符"""
# name = Manage("name")
def __init__(self, attrName):
self.attrName = attrName
def __set__(self, instance, value):
if type(value) is str:
print("字符串类型,正确", value, type(value))
# setattr(instance, self.attrName, value)
instance.__dict__[self.attrName] = value
else:
print("非法数据类型", value, type(value))
raise TypeError("{}是非法的数据类型".format(value))
# raise KeyError("{}是非法的数据类型".format(value))
def __get__(self, instance, owner):
pass
class People:
name = Manage("name")
def __init__(self,name):
# print('sq--self', self)
= name
# sq = People("孙权")
n = People(111)
# print(sq.__dict__)
print(n.__dict__)
# print('sq的地址', sq)