Python conditional assignment operator

前端 未结 10 1969
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 18:03

Does a Python equivalent to the Ruby ||= operator (\"set the variable if the variable is not set\") exist?

Example in Ruby :

 variable_n         


        
10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 18:44

    No, not knowing which variables are defined is a bug, not a feature in Python.

    Use dicts instead:

    d = {}
    d.setdefault('key', 1)
    d['key'] == 1
    
    d['key'] = 2
    d.setdefault('key', 1)
    d['key'] == 2
    

提交回复
热议问题