python - 为什么 __new__ 没有在我的 Python 类上被调用?

标签 python python-2.x

我有一个这样定义的类:

class Client():
    def __new__(cls):
        print "NEW"
        return cls

    def __init__(self):
        print "INIT"

当我使用它时,我得到以下输出:

cl = Client()
# INIT

__new__ 未被调用。为什么?

最佳答案

看完你的回答,我改进了它

class Client(object):
    def __new__(cls):
        print "NEW"
        return super(Client, cls).__new__(cls)
    def __init__(self):
        print "INIT"

这样c = Client()输出

NEW
INIT

如预期的那样。

关于python - 为什么 __new__ 没有在我的 Python 类上被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12638363/

相关文章:

python - print.__doc__ vs getattr(__builtin__ ,"print").__doc__

python - Unicode编码错误: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128)

python - 使用哪个三元运算符?

python - 将 DataFrame Pandas 中第二行的列分类到第一行?

python - Pandas 在组内填充缺失的日期和值

python - 如何在 PySide 的 QTreeView 中隐藏 QFileSystemModel 中的项目?

python - 在 MacOSX 上为 Eclipse 多次安装 Python

python - __add__ 两个类对象

python - 执行Python代码时自动打开浏览器

python - 如何在 Tensorflow 中有效使用 tf.bucket_by_sequence_length?