モジュールのサンプルコード:
somevar = "a"
def myfunc(somevar = None):
# need to access both somevars ???
# ... if somevar was specified print it or use the global value
pass
if __name__ == '__main__':
somevar = "b" # this is just for fun here
myfunc("c")
myfunc() # should print "a" (the value of global variable)
同じ名前を使用する理由は少なくとも2つあります。教育的(ローカル/グローバルの使用方法を学ぶため)とモジュールでの使用です。
このコードがモジュールの一部であるとしましょう:mymodule
そしてあなたは次のようなことをしたいと思います:
import mymodule
mymodule.samevar = "default"
...
mymodule.myfunc(somevar = "a")
...
mymodule.myfunc()
この例では単純化されていることが想像できるように、somevar
パラメーターが多くのオプションのパラメーターの1つであり、myfuncが多くの場所で呼び出されていることを想像してください。