Help us understand the problem. What is going on with this article?

Pythonのfoo['a'], foo.a, foo.get('a')の違い

Python始めたてでふわっとしていたので自分なりにまとめてみました。

環境

  • Python 3.7.3

色々試してみる

dictの場合

foo = {
    'a': 1, 'b': 2, 'c': 3
}

print(foo.get('a'))  # 1
print(foo.get('d'))  # None

print(foo['a'])  # 1
print(foo['d'])  # Exception has occurred: KeyError

print(foo.a)  # Exception has occurred: AttributeError
print(foo.d)  # Exception has occurred: AttributeError

# getだとExceptionが出ずに`None`を返してくれるので、if文とかで便利 
if foo.get('d') is None:
    print(True)

foo['d']でいけるならfoo.dでもいけそうな気がしてしまうjavascriptユーザー

クラス・インスタンスメソッドの場合

.でのアクセスは、
Pythonではクラスメソッド・インスタンスメソッドへアクセスでのみ使うことができるらしい。
ついでにgetはdictのメソッドなので使えない。

class Foo:
    bar = 'bar'

    def __init__(self):
        self.baz = 'baz'

foo = Foo()
print(foo.bar)  # bar(クラス変数)
print(foo.baz)  # baz(インスタン卯変数)
print(foo.get('bar')) # Exception has occurred: AttributeError
print(foo.get('baz')) # Exception has occurred: AttributeError
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away