gpt4 book ai didi

python - 访问 ETS Range 属性的低和高设置?

转载 作者:太空狗 更新时间:2023-10-30 02:58:32 26 4
gpt4 key购买 nike

这是一个使用 Enthought 工具套件 (ETS) 组件的交互式 Python session :

>>> import sys
>>> sys.version
'2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)]'
>>> import traits
>>> traits.__version__
'4.5.0'
>>> from traits.api import HasTraits, Range
>>> class Foo(HasTraits):
... bar = Range (low=1, high=10)
...
>>> foo = Foo()
>>> foo.bar
1
>>> foo.bar._low
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: 'int' object has no attribute '_low'

我希望能够访问 Foo 实例的 bar 属性的预定义限制。如何做到这一点?

谢谢!

最佳答案

执行此操作的标准方法是使用 lowhigh 特征并将它们分配为 Range 的限制

from traits.api import HasTraits, Range, Int


class Foo(HasTraits):
high = Int(10)
low = Int(1)
bar = Range(high='high', low='low')

您可以动态分配特征:

>>> f = Foo()
>>> f.bar = 5
>>> f.bar
5
>>> f.bar = 30
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/tim/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/traits/trait_types.py", line 1785, in _set
self.error( object, name, value )
File "/Users/tim/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/traits/trait_handlers.py", line 172, in error value )
traits.trait_errors.TraitError: The 'bar' trait of a Foo instance must be 1 <= a number <= 10, but a value of 30 <type 'int'> was specified.
>>> f.high = 35
>>> f.bar = 30
>>> f.bar
30

关于python - 访问 ETS Range 属性的低和高设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33679058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com