0

私はこれを持っています:

#! /usr/bin/env python

class myclass1(object):

        def __new__(cls,arg):
                print cls, arg, "in new"
                ss = super(object,cls)
                print ss, type(ss)
                ss.__new__(cls,arg)
#                super(object,cls).__new__(cls,arg)
#                return object.__new__(cls,arg)


        def __init__(self,arg):
                self.arg = arg + 1
                print self, self.arg, "in init"




if __name__ == '__main__':

        m = myclass1(56) 

エラーが発生します:

$ ./newtest.py 
<class '__main__.myclass1'> 56 in new
<super: <class 'object'>, <myclass1 object>> <type 'super'>
Traceback (most recent call last):
  File "./newtest.py", line 23, in <module>
    m = myclass1(56)
  File "./newtest.py", line 9, in __new__
    ss.__new__(cls,arg)
TypeError: super.__new__(myclass1): myclass1 is not a subtype of super

エラーは有効です。わかりました。しかし、__new__のこのページでドキュメントが何を言っているのか、私は今混乱しています: http://docs.python.org/2.6/reference/datamodel.html#object.__new__

質問: 上記のドキュメントによると、私は何を間違っていますか? ドキュメントに対する私の理解のギャップはどこにありますか?

4

2 に答える 2

1

Super は静的メソッドである__new__ため、通常は使用されません。__new__この時点では、オブジェクトはまだ存在していないため、呼び出すスーパーはありません。

オーバーライドする具体的な方法については、リリース ノートを参照してください。__new__

于 2013-08-25T00:22:21.853 に答える
1

object基本的にmyclass1inに置き換える必要がありss = super(object,cls)ます。 objectスーパークラスはありません。 myclass1します。パラメータが 1 つしかないためargs、 fromss.__new__(cls,args)も削除する必要があります。最終的なコードは次のようになります。object.__new__cls

        def __new__(cls,arg):
                print cls, arg, "in new"
                ss = super(myclass1,cls)
                print ss, type(ss)
                ss.__new__(cls)
#                super(object,cls).__new__(cls,arg)
#                return object.__new__(cls,arg)

ドキュメンテーションの理解のギャップは、最初のパラメーターがsuperそのスーパークラスを取得したいクラスであるということです。スーパークラスそのものではありません。スーパークラスをすでに知っているか、固定されたものをハードコーディングしたい場合は、置き換えssて次のようobjectに記述できます。

        def __new__(cls,arg):
                print cls, arg, "in new"
#               ss = super(myclass1,cls)
                print object, type(object)
                object.__new__(cls)
#                super(object,cls).__new__(cls,arg)
#                return object.__new__(cls,arg)
于 2013-08-25T00:20:56.937 に答える