【问题标题】:Can not assert type of an object?不能断言对象的类型?
【发布时间】:2026-02-12 11:25:03
【问题描述】:

为什么这个来源...

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

..?我希望类初始化器成为对象创建的苛刻过滤器。

你是怎么处理的?对我来说一切都很好。

【问题讨论】:

  • 您将实际类型对象与其字符串表示混淆了。

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


【解决方案1】:

我问了鸭子,然后我告诉鸭子我应该这样做

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

【讨论】:

  • 但是,这会产生“SyntaxWarning:断言始终为真,也许删除括号?”。直到今天才看到这种警告。
  • 你为什么要把这个告诉鸭子?多一点解释可能会更好。
  • 我想鸭子是让你这么做的。这可能有效,但根本不是一个好方法......
  • 我的意思是我应该把鸭子放在我的手牌范围内,我忘了在问筹码之前告诉鸭子。
【解决方案2】:

与其比较type(你当然不应该将其作为字符串!),不如使用isinstance。另外,你不应该像这样使用assert,试试这样的:

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

【讨论】:

  • 我需要的智慧。
  • 扩展 jonrsharpe 的评论:您应该使用 assert 来检测程序中的错误数据 - 为此使用 iftryassert 用于捕获程序逻辑中的错误。用户不应仅仅因为输入了错误数据而从您的程序中看到断言错误。如果用户看到断言错误,则意味着您的逻辑中存在错误,您需要为他们修复程序。
最近更新 更多