无法断言对象的类型?

时间:2014-09-17 08:05:10

标签: python python-3.x metaprogramming python-2.x metaclass

为什么这个来源...

"""
[...]
"""
#   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
$ _

..?我希望类初始化程序是一个用于创建对象的严格过滤器。

你是如何处理的?这对我来说似乎都没问题。

2 个答案:

答案 0 :(得分:3)

使用isinstance,而不是与type(您当然不应该作为字符串进行比较!)进行比较。此外,你不应该像这样使用assert,尝试类似:

if not isinstance(date, dt): # note you have aliased datetime.datetime
    raise TypeError(...)

答案 1 :(得分:-2)

我问鸭子,然后我告诉我应该做的鸭子

        assert (str(type(date)) == "<class 'datetime.datetime'>",
                'assertion failed creating a CuteClass object')

而不是

        assert (type(date) == "<class 'datetime.datetime'>",
                'assertion failed creating a CuteClass object')