|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class Integer:
- def __init__(self, name):
- self.name = name
- def __get__(self, instance, cls):
- if instance is None:
- return self
- else:
- return instance.__dict__[self.name]
- def __set__(self, instance, value):
- if not isinstance(value, int):
- raise TypeError('Expected an int')
- instance.__dict__[self.name] = value
- def __delete__(self, instance):
- del instance.__dict__[self.name]
- class Point:
- x = Integer('x')
- y = Integer('y')
- def __init__(self, x, y):
- self.x = x
- self.y = y
- p = Point(2.3, 3)
复制代码
我知道错误原因是因为输入了浮点,只能接受整数。但是没搞懂的是为什么x会调用另外一个类?不应该是直接做初始化嘛?这段一点都没搞明白一头雾水
因为 - class Point:
- x = Integer('x')
- y = Integer('y')
- def __init__(self, x, y):
- self.x = x
- self.y = y
复制代码
在这一段代码中
- x = Integer('x')
- y = Integer('y')
复制代码
属于是全局变量,是先于__init__方法执行的
|
|