在Python中使用__new__方法

5

我是新手学习Python,正在尝试使用类。我确实理解__init____new__之间的区别。这里是我的一个类片段:

class Vector2D:

    def __new__(cls):
        print "Testing new"
        return super(Vector2D,cls).__new__(cls)

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return "X:" + str(self.x) + ",Y:" + str(self.y)

我正在按照以下方式初始化类,并期望首先打印出 "Testing new":
def Main():
    vec = Vector2D(1,2)
    print "Printing vec:",vec

但我只得到了输出。
Printing vec: X:1,Y:2

__new__()方法中,我需要做什么才能打印出"Testing new"?

谢谢。


1
class Vector2D: ===> class Vector2D(object): - Kit Fung
@WillVousden 我在 Stack 上不得不缩进几次才能获得代码样式。 - Ayubx
@KitFung 谢谢。将 class Vector2D: 改为 class Vector2D(object): 解决了问题,但我还需要将参数从 def __new__(cls): 改为 def __new__(cls,x,y): - Ayubx
如果我理解你回答的最后一部分,即“但是您的超类(对象)在其__new__方法中不需要任何参数,因此不要将它们传递给上层”,您的意思是这样做:def __new__(cls, *args, **kw)而不是def __new__(cls, x,y) - Ayubx
1
@Ayubx,def __new__(cls, x, y) 也可以正常工作,但如果你将 __init__ 添加了更多参数,你也必须将它们添加到 __new__ 中。我写的版本是通用的,所以它会忽略任何参数,无需进一步编辑。无论哪种方式在这里都是可接受的。 - Duncan
显示剩余2条评论
1个回答

8
你需要将你的Vector2D类作为object的子类,否则很多东西会出现问题。这些问题包括__new__super
以下代码应该可以正常运行:
class Vector2D(object):
    def __new__(cls, *args, **kw):
        print "Testing new"
        return super(Vector2D,cls).__new__(cls)


    def __init__(self, x, y):
        self.x = x
        self.y = y


    def __str__(self):
        return "X:" + str(self.x) + ",Y:" + str(self.y)

请注意,当您构建实例时使用的参数会同时传递给 __new____init__ 方法,因此您必须准备在 __new__ 中接受它们。但是,您的超类(object)的 __new__ 方法不接受任何参数,因此请勿将其上推至链条中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接