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

时间:2015-11-12 18:51:00

标签: python range enthought

这是一个交互式Python会话,它使用Enthought Tool Suite(ETS)的组件:

>>> 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'

我希望能够访问bar实例的Foo属性的预定义限制。怎么办呢?

谢谢!

2 个答案:

答案 0 :(得分:2)

Range()对象具有_low_high属性,可以访问这些属性。 我想使用它们的下划线,以便它不会与low中的highRange()个关键字参数生成阴影。

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

仍然可以将它们作为类实例属性进行访问,但是您需要知道变量的名称(在此基础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

答案 1 :(得分:2)

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