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

Access low and high settings of an ETS Range attribute?

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

>>> 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 属性的预定义限制。如何做到这一点?

谢谢!

Range()对象有_low_high属性,可以访问。 我想它们的下划线被使用,这样它就不会与 Range() 中的 lowhigh 关键字参数重叠。

>>> import traits.api
>>> bar = traits.api.Range(low=1, high=10)
>>> bar._low
1
>>> bar._high
10

仍然可以将它们作为 class 实例属性访问,但是您需要知道变量的名称(在此基础 bar 中),以便您可以在 foo.traits(),这是所有特征的字典:

>>> foo = Foo()
>>> foo.traits()['bar'] # dictionary of all traits
<traits.traits.CTrait object at 0x000000000525A6D8>
>>> foo.traits()['bar'].trait_type
<traits.trait_types.Range object at 0x0000000005BA3EF0>
>>> foo.traits()['bar'].trait_type._low
1
>>> foo.traits()['bar'].trait_type._high
10

执行此操作的标准方法是使用 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