Python`is_trait_type`不适用于`Date` [英] Python `is_trait_type` doesn't work with `Date`
问题描述
在我工作的项目中,我们经常需要将文本转换为特征的值。通常,我们使用 is_trait_type
方法来进行适当的转换。
但是,它不适用于日期
traits。这是一个MWE:
从traits.has_traits导入HasTraits
from traits.trait_types import Int,Date
class A(HasTraits):
a_date = Date
an_int = Int
a = A()
class_traits = a.class_traits()
print class_traits [an_int]。is_trait_type(Int)
print class_traits [a_date]。is_trait_type(Date)
Int
的行为符合预期,但 Date
失败:
TypeError:isinstance()arg 2必须是类和类型的类,类型或元组
我们在Ubuntu 14.04下使用Enthought traits
module(版本4.1.0)。
如评论中所述, Date
(和时间
)trait类型不是类,而是实例。 is_trait_type(x)
方法检查 self.trait_type
是否是提供的类的实例(即 x
),因此如果 x
不是一个类,它将失败。在我看来,这是API中的一个错误。
如果需要解决方法,您可以定义一个这样的方法:
pre>
def my_is_trait_type(trait,trait_type):
if isinstance(trait_type,BaseInstance):
return trait.is_trait_type(trait_type .__ class__)
else:
return trait.is_trait_type(trait_type)
然而,我会重新考虑使用 is_trait_type()
用于查找适当转换的任务。例如,可能会出现地图。
In the project I work for, we often need to convert text to the value of a trait. Generally, we use the is_trait_type
method to do the appropriate conversion.
However, it doesn't work with Date
traits. Here is a MWE:
from traits.has_traits import HasTraits
from traits.trait_types import Int, Date
class A(HasTraits):
a_date = Date
an_int = Int
a = A()
class_traits = a.class_traits()
print class_traits["an_int"].is_trait_type(Int)
print class_traits["a_date"].is_trait_type(Date)
The Int
behave as expected but the Date
fails with:
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
We use Enthought traits
module (version 4.1.0) under Ubuntu 14.04.
As mentioned in the comments, Date
(and Time
) trait types are not classes but instances. The is_trait_type(x)
method checks whether self.trait_type
is an instance of the provided class (i.e. the value of x
), and hence it fails if x
is not a class. In my opinion, this a bug in the API.
If you need a workaround, you can define a method like this:
def my_is_trait_type(trait, trait_type):
if isinstance(trait_type, BaseInstance):
return trait.is_trait_type(trait_type.__class__)
else:
return trait.is_trait_type(trait_type)
However, I would reconsider using is_trait_type()
for the task of finding the appropriate conversion. Maybe a map would do, for instance.
这篇关于Python`is_trait_type`不适用于`Date`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!