Q&A
実現したいこと
下記のコードでmatch構文上だとdataclassを未適用時でもPoint(x=0,y=0)の記述方法が可能で、match構文外で同じように宣言するとエラーが発生します。これは何故でしょうか?
python
1class Point: 2 x: int 3 y: int 4 5def where_is(point): 6 match point: 7 case Point(x=0, y=0): 8 print("Origin") 9 case Point(x=0, y=y): 10 print(f"Y={y}") 11 case Point(x=x, y=0): 12 print(f"X={x}") 13 case Point(): 14 print("Somewhere else") 15 case _: 16 print("Not a point") 17if __name__ == "__main__": 18 point = Point(x=0, y=0) # 失敗する、がdataclassをPointに適用したら成功する 19 point.x, point.y = (0,0) # 成功する 20 where_is(point)
python
1Traceback (most recent call last): 2 File "/hogehoge/hoge.py", 3 point = Point(x=0, y=0) 4 ^^^^^^^^^^^^^^^ 5TypeError: Point() takes no arguments
回答3件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。