スペシャルメソッドを挙動を確認しています。
クラスのインスタンス化するときは、カッコつきでインスタンス化するはずですが、type()の結果がNone Typeになり、カッコなしでインスタンス化した場合には、type()がtypeになります。
なぜ、カッコつきでインスタンス化できないのか、またカッコなしでインスタンス化したときの<class 'type'>は何を指しているのか、についてご教示いただけませんでしょうか?
__call__メソッドについても勉強していますが、なんのために存在し、どう利用できるかも理解できずにいます。
__init__とnewの違いは理解しています。
python
1class SpecialMethods: 2 print("class variable") 3 4 def __init__(self): 5 print("print method in __init__") 6 7 def __new__(self): 8 print("print method in __new__") 9 10 def __call__(self): 11 print("print method in __call__")
実行結果
$ python Python 3.9.2 (v3.9.2:1a79785e3e, Feb 19 2021, 09:06:10) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from xxx import SpecialMethods class variable >>> cls = SpecialMethods() print method in __new__ >>> type(cls) <class 'NoneType'> >>> cls = SpecialMethods >>> type(cls) <class 'type'>
回答2件
あなたの回答
tips
プレビュー