不能断言对象的类型? [英] Can not assert type of an object?
本文介绍了不能断言对象的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这个来源...
"""
[...]
"""
# Import the standard date and time system.
from datetime import datetime as dt
# Ommited the remaining imports section
class CuteClass(object):
"""
[...]
"""
def __init__(self, parameter_zero, date, parameter_two):
"""
[...]
"""
# Omitted parameter_zero processing.
print(type(date)) # FIXME delete this sentence.
if sys.version_info[0] == 2:
assert (type(date) == "<type 'datetime.datetime'>",
'assertion failed creating a CuteClass object')
elif sys.version_info[0] == 3:
assert (type(date) == "<class 'datetime.datetime'>",
'assertion failed creating a CuteClass object')
else:
sys.exit(inspect.getframeinfo(inspect.currentframe()))
self.date = date
# Omitted remaining parameters' processing.
... python3
...
<class 'datetime.datetime'>
Traceback (most recent call last):
[...]
File "...", line 37, in __init__
assert type(date) == "<class 'datetime.datetime'>"
AssertionError
$ _
..?我希望类初始值设定项成为对象创建的严格过滤器.
..? I want the class initializer be a harsh filter for object creation.
你是怎么处理的?对我来说这一切似乎都很好.
How do you deal with that? It all seems to be OK to me.
推荐答案
与其与 type
进行比较(您当然不应该将其作为字符串!),请使用 isinstance
.另外,您不应该像那样使用 assert
,请尝试以下操作:
Rather than comparing to type
(which you certainly shouldn't do as a string!), use isinstance
. Also, you shouldn't use assert
like that, try something like:
if not isinstance(date, dt): # note you have aliased datetime.datetime
raise TypeError(...)
这篇关于不能断言对象的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文