super and __new__ confusion

两盒软妹~` 提交于 2019-11-30 10:59:41

问题


As what I just learned, I can use super() this way:
super(class, obj_of_class-or-_subclass_of_class)

Code goes below:

#Case 1
class A(object):
    def __init__(self):
        print "A init"

class B(A):
    def __init__(self):
        print "B init"
        super(B, self).__init__()  #ok, I can invoke A's __init__ successfully

#Case 2
class A(object):
    @classmethod
    def foo(cls):
        print "A foo"

class B(object):
    @classmethod
    def foo(cls):
        print "B foo"
        super(B, cls).foo()   #ok, I can invoke A's foo successfully

#Case 3
class A(object):
    def __new__(cls):
      print "A new"
      return super(A, cls).__new__(cls)

class B(A):
    def __new__(cls):
      print "B new"
      return super(B, cls).__new__()  #Oops, error

QUESTION:

In case 1 and 2, I can use super successfully without specifying the obj or cls to operate on. But why can't I do the same for __new__? Because, in case 3, if I use super that way, I got an error. But if I use it this way:

super(B, cls).__new__(cls)

No error.


回答1:


From the Python release notes on overriding the __new__ method:

__new__ is a static method, not a class method. I initially thought it would have to be a class method, and that's why I added the classmethod primitive. Unfortunately, with class methods, upcalls don't work right in this case, so I had to make it a static method with an explicit class as its first argument.

Since __new__ is a static method, super(...).__new__ returns a static method. There is no binding of cls to the first argument in this case. All arguments need to be supplied explicitly.



来源:https://stackoverflow.com/questions/7471255/super-and-new-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!