Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法断言对象的类型?_Python_Python 3.x_Metaprogramming_Python 2.x_Metaclass - Fatal编程技术网

Python 无法断言对象的类型?

Python 无法断言对象的类型?,python,python-3.x,metaprogramming,python-2.x,metaclass,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, paramete

为什么这个来源

"""
[...]
"""
#   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.
。。?我希望类初始值设定项是对象创建的严格过滤器


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

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

        assert (str(type(date)) == "<class 'datetime.datetime'>",
                'assertion failed creating a CuteClass object')
assert(str(type(date))==“”,
'断言创建CuteClass对象失败')
而不是

        assert (type(date) == "<class 'datetime.datetime'>",
                'assertion failed creating a CuteClass object')
assert(类型(日期)==”,
'断言创建CuteClass对象失败')

不要将其与
类型进行比较(您当然不应该将其作为字符串执行!),而是使用。此外,您不应该像那样使用
assert
,请尝试以下操作:

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

然而,这会产生“SyntaxWarning:断言总是正确的,也许删除括号?”。直到今天才读过这样的警告。你为什么要告诉鸭子?多解释一点可能更好。我想是鸭子让你这么做的。这可能有用,但根本不是一个好方法……我的意思是我应该让鸭子在我手的范围内,我忘了在问stack之前告诉鸭子。我需要的智慧。要扩展jonrsharpe的评论:你不应该使用
断言
来检测程序中的坏数据-如果
使用
,或者
尝试
<代码>断言
用于捕获程序逻辑中的错误。用户不应该仅仅因为输入了错误数据就看到程序中的断言错误。如果用户看到断言错误,这意味着您的逻辑中存在错误,您需要为其修复程序。您将实际的类型对象与其字符串表示形式混淆。
if not isinstance(date, dt): # note you have aliased datetime.datetime
    raise TypeError(...)