类型错误:__init__() 应该返回 None,而不是 'int' [英] TypeError: __init__() should return None, not 'int'

查看:427
本文介绍了类型错误:__init__() 应该返回 None,而不是 'int'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理这个教程.我正在迭代地解决这个问题.此时我有以下 Binary 类:

I'm working through this tutorial. I'm working through this iteratively. At this point I have the following Binary class:

class Binary:
    def __init__(self,value):
        self.value = str(value)
        if self.value[:2] == '0b':
            print('a binary!')
            self.value= int(self.value, base=2)
        elif self.value[:2] == '0x':
            print('a hex!')
            self.value= int(self.value, base=16)
        else:
            print(self.value)
        return int(self.value)

我正在使用 pytest 运行一套测试,包括:

I'm running through a suite of tests using pytest, including:

    def test_binary_init_hex():
        binary = Binary(0x6)
        assert int(binary) == 6
      E TypeError: int() argument must be a string or a number, not 'Binary'

我问了一个关于这个的问题 TypeError: int() 参数必须是字符串或数字,而不是 'Binary' 并根据答案将代码更改为如上.现在,当我使用 pytest 运行测试套件时,所有测试都失败了,错误是:

I asked a question about this TypeError: int() argument must be a string or a number, not 'Binary' and based on the answer changed the code to as above. Now when I run the suite of tests using pytest, all the tests fail and the error is:

       TypeError: __init__() should return None, not 'int'

为什么会出现问题?

推荐答案

在提供任何答案之前,我评论您 __init__() 用于初始化对象,因此您不得返回任何值其中.但是很奇怪看到上面的一些赞成的答案要求不要在 __init__() 中返回值,但他们的解决方案仍然不尊重他们所说的.只有 @CPanda 没有做与他所说的相反的事情.这就是为什么我要再次强调作为答案:

Before any answer was provided, I commented you that __init__() is used to initialize objects and thus you must not return any value within it. But it is strange to see some of the upvoted answers above asked not to return values within __init__() but still their solution does not respect what they said. Only @CPanda did not do the opposite of what he said. That is why I want to highlight this again as answer:

在创建实例之后调用(通过 __new__()),但在此之前它返回给调用者.参数是传递给类构造函数表达式.如果基类有一个 __init__()方法,派生类的 __init__() 方法,如果有,必须显式调用它以确保正确初始化基类部分实例;例如:BaseClass.__init__(self, [args...]).

Called after the instance has been created (by __new__()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class's __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: BaseClass.__init__(self, [args...]).

因为 __new__()__init__() 在构造对象时协同工作(new() 来创建它,而 __init__() 自定义),没有__init__() 可以返回 non-None 值;这样做会导致TypeError 在运行时引发.

Because __new__() and __init__() work together in constructing objects (new() to create it, and __init__() to customise it), no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.

所以不要使用 __init__() 返回值!

So do NOT return values using __init__()!

我想补充的另一件事,即使在<中没有提到AFAIKem>Python 增强建议,我个人从不使用 __init__() 使用 print''/ 打印消息打印('').我在 __init__() 中打印的唯一消息是与引发异常错误消息相关的消息,例如 raise ValueError()(检查 内置异常了解更多信息)

An other thing I want to add, even if this is not mentioned AFAIK in Python Enhancement Proposals, I personally never use __init__() to print messages using print''/print(''). The only messages I print in __init__() are those related to raised exception error messages in a forms such as raise ValueError() (check Built-in Exceptions for more information)

这篇关于类型错误:__init__() 应该返回 None,而不是 'int'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆