- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我使用描述符编写了一个 Circle 类,允许用户设置圆的 x、y 和 r 的值,并检查 x 和 y 的值是否为整数。如果用户输入非整数,则会引发 TypeError,现在我想制作另一个描述符类,允许用户获取圆的面积和周长的值,但无法设置它。我想我的 __get__
方法工作正常,但 __set__
方法不是。
class Integer:
def __init__(self, name):
self.name = name # stores name of the managed object's attribute
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')
else:
instance.__dict__[self.name] = value
class Computations(object):
def __init__(self, name):
self.name = name # default value for area, circumference, distance to origin
def __get__(self, instance, cls):
if instance is None:
print('this is the __get__ if statement running')
return self
else:
print('this is the __get__ else statement running')
return instance.__dict__[self.name]
def __set__(self, instance, value):
if isinstance(value, int):
raise RuntimeError('Cant set formulas')
else:
instance.__dict__[self.name] = value
class Circle:
x = Integer('_x') # Use _x and _y as the __dict__ key of a Point
y = Integer('_y') # These will be the storage names for a Point
r = Integer('_r')
area = Computations('_area') # class variable of Computations
circumference = Computations('_circumference')
distance_to_origin = Computations('_distance_to_origin')
def __init__(self, x, y, r):
self.x = x # invokes Integer.x.__set__
self.y = y # invokes Integer.y.__set__
self.r = r # for radius/invokes Integer.r.
self.area = pi * self.r * self.r
self.circumference = 2 * pi * self.r
self.distance_to_origin = abs(sqrt((self.x - 0)*(self.x - 0) + (self.y - 0) * (self.y - 0)) - self.r)
# Testing code
if __name__ == '__main__':
circle = Circle(x=3, y=4, r=5)
print(circle.x)
print(circle.y)
print(circle.r)
print(circle.area)
# circle.area = 12
print(circle.area)
print(circle.circumference)
print(circle.distance_to_origin)
tests = [('circle.x = 12.3', "print('Setting circle.x to non-integer fails')"),
('circle.y = 23.4', "print('Setting circle.y to non-integer fails')"),
('circle.area = 23.4', "print('Setting circle.area fails')"),
('circle.circumference = 23.4', "print('Setting circle.circumference fails')"),
('circle.distance_to_origin = 23.4', "print('Setting circle.distance_to_origin fails')"),
('circle.z = 5.6', "print('Setting circle.z fails')"),
('print(circle.z)', "print('Printing circle.z fails')")]
for test in tests:
try:
exec(test[0])
except:
exec(test[1])
程序运行,但它允许设置面积、周长和到原点的距离,这不是我想要的。我知道行 "if isinstance(value, int): raise RuntimeError('Can't set formulas')"
意味着如果用户输入的值不是整数,那么它会引发一个错误。我只是不确定用什么来代替它,这样它就会抛出错误并且不允许用户更改值。
测试代码正确输出如下:
78.53981633974483
31.41592653589793
0.0
Setting circle.x to non-integer fails
Setting circle.y to non-integer fails
Setting circle.area fails
Setting circle.circumference fails
Setting circle.distance_to_origin fails
5.6
最佳答案
这将只允许对Computations
描述符进行初始设置:
class Computations(object):
def __init__(self, name):
self.name = name # default value for area, circumference, distance to origin
def __get__(self, instance, cls):
if instance is None:
print('this is the __get__ if statement running')
return self
else:
print('this is the __get__ else statement running')
return instance.__dict__[self.name]
def __set__(self, instance, value):
if hasattr(instance, self.name + '_is_set'):
raise ValueError('Cannot set {} again.'.format(self.name[1:]))
if isinstance(value, int):
raise RuntimeError('Cant set formulas')
else:
instance.__dict__[self.name] = value
setattr(instance, self.name + '_is_set', True)
诀窍是在实例上生成一个新属性:
setattr(instance, self.name + '_is_set', True)
对于实例 circle
和属性 circumference
这意味着:
circle._circumference_is_set = True
检查这个属性是否存在:
if hasattr(instance, self.name + '_is_set')
对于我们的案例,这意味着:
if hasattr(circle, '_circumference_is_set')
第一次 __set__
被 circumference
调用是在 Circle
类中:
self.circumference = 2 * pi * self.r
现在 _circumference_is_set
存在,下次尝试设置它会导致异常。
你的代码和我的新描述符计算
:
from math import pi, sqrt
class Integer(object):
def __init__(self, name):
self.name = name # stores name of the managed object's attribute
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')
else:
instance.__dict__[self.name] = value
class Computations(object):
def __init__(self, name):
self.name = name # default value for area, circumference, distance to origin
def __get__(self, instance, cls):
if instance is None:
print('this is the __get__ if statement running')
return self
else:
print('this is the __get__ else statement running')
return instance.__dict__[self.name]
def __set__(self, instance, value):
if hasattr(instance, self.name + 'is_set'):
raise ValueError('Cannot set {} again.'.format(self.name[1:]))
if isinstance(value, int):
raise RuntimeError('Cant set formulas')
else:
instance.__dict__[self.name] = value
setattr(instance, self.name + 'is_set', True)
class Circle(object):
x = Integer('_x') # Use _x and _y as the __dict__ key of a Point
y = Integer('_y') # These will be the storage names for a Point
r = Integer('_r')
area = Computations('_area') # class variable of Computations
circumference = Computations('_circumference')
distance_to_origin = Computations('_distance_to_origin')
def __init__(self, x, y, r):
self.x = x # invokes Integer.x.__set__
self.y = y # invokes Integer.y.__set__
self.r = r # for radius/invokes Integer.r.
self.area = pi * self.r * self.r
self.circumference = 2 * pi * self.r
self.distance_to_origin = abs(sqrt(self.x * self.x + self.y * self.y) - self.r)
现在尝试设置 circle.circumference
会引发异常:
# Testing code
if __name__ == '__main__':
circle = Circle(x=3, y=4, r=5)
print('circumference', circle.circumference)
print('try setting circumference')
circle.circumference = 12.5
输出:
this is the __get__ else statement running
circumference 31.41592653589793
try setting circumference
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-227-316199bab738> in <module>()
64
65 print('try setting circumference')
---> 66 circle.circumference = 12.5
<ipython-input-227-316199bab738> in __set__(self, instance, value)
31 def __set__(self, instance, value):
32 if hasattr(instance, self.name + 'is_set'):
---> 33 raise ValueError('Cannot set {} again.'.format(self.name[1:]))
34 if isinstance(value, int):
35 raise RuntimeError('Cant set formulas')
ValueError: Cannot set circumference again.
你的测试:
if __name__ == '__main__':
circle = Circle(x=3, y=4, r=5)
print(circle.x)
print(circle.y)
print(circle.r)
print(circle.area)
# circle.area = 12
print(circle.area)
print(circle.circumference)
print(circle.distance_to_origin)
tests = [('circle.x = 12.3', "print('Setting circle.x to non-integer fails')"),
('circle.y = 23.4', "print('Setting circle.y to non-integer fails')"),
('circle.area = 23.4', "print('Setting circle.area fails')"),
('circle.circumference = 23.4', "print('Setting circle.circumference fails')"),
('circle.distance_to_origin = 23.4', "print('Setting circle.distance_to_origin fails')"),
('circle.z = 5.6', "print('Setting circle.z fails')"),
('print(circle.z)', "print('Printing circle.z fails')")]
for test in tests:
try:
exec(test[0])
except:
exec(test[1])
生成此输出:
3
4
5
this is the __get__ else statement running
78.53981633974483
this is the __get__ else statement running
78.53981633974483
this is the __get__ else statement running
31.41592653589793
this is the __get__ else statement running
0.0
Setting circle.x to non-integer fails
Setting circle.y to non-integer fails
Setting circle.area fails
Setting circle.circumference fails
Setting circle.distance_to_origin fails
5.6
关于python - 当用户尝试更改对象的值时使用描述符类引发 RuntimeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34478011/
我正在使用 SharePoint Online 并使用 Windows Azure 托管访问 SPO 的进程。 我们已将启动任务添加到 Azure 角色以安装 http://www.microsoft
我有一个函数,它获取包含时间的源文件(csv 文件),读取它,然后按顺序对行进行排序并将它们写入目标文件中。但是,如果源 csv 文件不存在,我需要引发 FileNotFoundError。我之前曾引
我试图在目录不存在时引发错误,然后再打开该目录中的文件。根据this response我应该为我的问题使用最具体的异常构造函数,我认为它是 NotADirectoryError。但是运行下面的代码我得
在编码/开发生命的一天或另一天,我们确实遇到了这个特殊的情况,这是最常见的异常(exception)之一。我的问题是关于的而不是。为什么(我知道当我们尝试访问实际上指向null的引用变量的属性时会引发
我想知道在 python 中是否可以在一个 except block 中引发异常并在稍后的 except block 中捕获它。我相信其他一些语言默认会这样做。 这是它的样子" try: som
我有以下代码: br = mechanize.Browser() br._factory.is_html = True br.form = mechanize._form.ParseString(''
我刚刚发现,如果您有一个引发 TOO_MANY_ROWS 异常的 SELECT INTO,该变量仍会从查询检索到的第一条记录中分配值。这是预期的行为吗? 这是我的例子: for co in my_cu
当 SSH 显示 WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! 我知道当您重新安装远程服务器时会发生这种情况,但我尝试列出 其他原因 . 我知道如何
我有一个枚举和一个 EnumMap . 我将 map 放入一个类中以隐藏“字节”值。所以我有一个set(Parameter, int)和set(Parameter, boolean)方法。 publi
在什么情况下会redis-py引发以下 AttributeError 异常? redis-py 不是设计来引发仅基于 redis.exceptions.RedisError 的异常吗? 什么是合理的处
可悲的是,对此异常的引用通常具有异国情调,并且可能发生在您例如通过 Assembly.GetTypes() 枚举类型- 举个例子,它发生在我们的一个部署上,但同一组程序集在集成服务器上运行良好。 为了
我正在为 Android 下的特定平板电脑克隆一个存储库并获取源代码,我必须执行一个 python 脚本。当我执行它时,我收到此错误消息: Traceback (most recent call la
首先,执行此操作(在运行 4.4.2 的 Nexus 5 上测试): 将 PRIORITY_LOW 通知传递给 Service.startForeground()。 观察通知不显示在状态栏中。 使用相
我尝试使用 AppEngine 的 python 模块 api 来获取使用基本缩放的模块的实例数。在我模块的 yaml 文件中,我明确设置了 max_instances 参数。我希望 get_num_
当我如下运行我的 spark python 代码时: import pyspark conf = (pyspark.SparkConf() .setMaster("local")
在我的系统上,一段适用于 Python 2 的代码不适用于 Python 3。 f = open("plotwidget.svg") svgData = f.read() xml_stream = Q
我是 PHP 和 SQL 的新手,但我正在创建一个登录系统。我遇到的问题是: You have an error in your SQL syntax; check the manual that c
我有一个使用 ebaysdk 库的 python 代码,当我运行代码并输入关键字进行搜索时,我得到了这个错误。 Traceback (most recent call last): File "eba
当我将表单数据发送到我的 Flask 应用程序时,出现以下错误。它说它将使用 UTF-8 编码,但语言环境已经是 UTF-8。这个错误是什么意思? /home/.virtualenvs/project
在python2.7中,跟随pympler example : from anotherfile import somefunction, somecustomclass from os import
我是一名优秀的程序员,十分优秀!