1
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)

Posted at

関数のデフォルト引数は一度しか評価されない(python)

  • 関数のデフォルト引数は__定義された時一度しか評価されない__ので注意が必要
  • 以下の例だと、get_numが宣言された時のnums(=0)がiのデフォルト値になり、途中で更新されることはない
nums = 0

def get_num(i=nums):
	print(i)

get_num()	# 0
nums=10
get_num() # 0
get_num(34) # 34
  • これはクラス内のメソッドでも同じで、クラス及びそのメソッドが宣言された時一度だけ評価される
nums = 0

class A:
    def get_num(self,i=nums):
        print(i)

a = A()
a.get_num() # 0

nums=10

b = A()
b.get_num() # 0

b.get_num(34) # 34
1
0
1

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
1
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?