Pythonのデータモデルについて学ぶ際に、私はメソッドを使用して既存のオブジェクトからオブジェクトを作成することで遊んでいます__new__
。さまざまなタイプの新しいオブジェクトを作成するいくつかの例を次に示します。
x = 2; print type(x).__new__(x.__class__)
x = {}; print type(x).__new__(x.__class__)
x = [1,2]; print type(x).__new__(x.__class__)
x = 2.34; print type(x).__new__(x.__class__)
x = '13'; print type(x).__new__(x.__class__)
x = 1.0j; print type(x).__new__(x.__class__)
x = True; print type(x).__new__(x.__class__)
x = (1,2); print type(x).__new__(x.__class__)
ただし、次の3つの実験ではエラーが発生します。
x = None; print type(x).__new__(x.__class__)
x = lambda z: z**2; print type(x).__new__(x.__class__)
x = object; print type(x).__new__(x.__class__)
エラーは(それぞれ)次のとおりです。
TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__()
TypeError: Required argument 'code' (pos 1) not found
TypeError: type() takes 1 or 3 arguments
これらの3つの例が機能しないのはなぜですか?(注:このlambda
例では、メソッドを呼び出すときにコードフラグメントを渡す必要があるようですが、その__new__
方法がわかりません。)Python2.6を使用しています。
これは必ずしも実際のコードで新しいオブジェクトを作成する方法ではないことに注意してください。しかし、私の目的は実用的ではなく、低レベルのオブジェクトメソッドがどのように機能するかを理解することです。