Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
このようにオブジェクトのプロパティにアクセスしたい
'region' :obj.region ? obj.region.name : "None"
問題は私のクラスにあります。obj.region が存在しない場合、リージョンに何も必要ありません。しかし、地域が関連付けられている場合は、地域の名前が必要です。
リージョンは true false ではありませんが、オブジェクトです
どうすればそれができますか
コメントで指摘されているように:
'region': obj.region.name if obj.region else "None"
しかし、次のようになっても驚かないでしょう。
'region': obj["region"]["name"] if "region" in obj and obj["region"] else "None"
正確に何であるかに応じてobj-それが実際のオブジェクトか辞書か。
obj