本站消息

  本站每日ip已达10000,出租广告位,位置价格可谈,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Inheritance when __new__() doesn't return instance of class in python 2.7.12

发布于2020-05-16 20:57     阅读(1081)     评论(0)     点赞(28)     收藏(2)


I've been reading about when __new__() doesn't return instance of class on stackoverflow Inheritance when __new__() doesn't return instance of class and I know this question is for python 3. As Martijn Pieters states, it can be done by name mangling and call it manually directly in the class and initialised it altogether in the class.

I want try it in python 2.7.12. The first and second approach I can manage, but for the third approach raises a TypeError.

This is my code, first attempt:

class A:
    def __new__(cls, p1, p2):
        self = object.__new__(cls)
        self.p1 = p1
        self.p2 = p2
        return [self]

class B(A):
    def __new__(cls, p3):
        self = super(B,cls).__new__(cls,1,2)
        self[0].p3 = p3
        return self

This gives me TypeError: super() argument 1 must be type, not classobj

Second attempt:

class A(object):
    def __new__(cls, p1, p2):
        self = object.__new__(cls)
        self.p1 = p1
        self.p2 = p2
        return [self]  #return not instance

class B(A):
    def __new__(cls, p3):
        self = super(B,cls).__new__(cls,1,2)
        self[0].p3 = p3
        return self

This gives me TypeError: __new__() takes exactly 2 arguments (1 given).

Why does this happen, can this be implemented in python 2.7.12 or this technique incompatible?


解决方案


In your first attempt, you are passing in an old-style class object, but super() only accepts new-style classes.

You need to inherit from object to get a new-style class, which you correctly did in your second attempt. You merely forgot to pass in an argument when creating an instance:

>>> class A(object):
...     def __new__(cls, p1, p2):
...         self = object.__new__(cls)
...         self.p1 = p1
...         self.p2 = p2
...         return [self]
...
>>> class B(A):
...     def __new__(cls, p3):
...         self = super(B, cls).__new__(cls, 1, 2)
...         self[0].p3 = p3
...         return self
...
>>> B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() takes exactly 2 arguments (1 given)
>>> B(42)
[<__main__.B object at 0x10241fa90>]

Your error told you that B.__new__ wanted two arguments, but only cls was being passed in.



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接: https://www.pythonheidong.com/blog/article/375063/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

28 0
收藏该文
已收藏

评论内容:(最多支持255个字符)