2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-06-20

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
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?