I got a piece of code like this:
foo = None
def outer():
global foo
foo = 0
def make_id():
global foo
foo += 1
return foo
id1 = make_id() # id = 1
id2 = make_id() # id = 2
id3 = make_id() # ...
I find it ugly to have foo
defined in the outermost scop, I would prefer to have it only in outer
function. As I understand correctly, in Python3 this is done by nonlocal
. Is there a better method for what I want to have? I would prefer to declare and assign foo
in outer
and maybe to delcare it global
in inner
:
def outer():
foo = 0
def make_id():
global foo
foo += 1 # (A)
return foo
id1 = make_id() # id = 1
id2 = make_id() # id = 2
id3 = make_id() # ...
(A) does not work, foo
seems to be searched in the outermost scope.
I use 1-element lists for this purpose:
def outer():
foo = [0]
def make_id():
r = foo[0]
foo[0] += 1
return r
return make_id
make_id = outer()
id1 = make_id()
id2 = make_id()
...
This is the same as using nonlocal
, at the cost of a slightly more cumbersome syntax ( foo[0]
instead of foo
).
No, have this as a parameter to your make_id
function. Even better put your id in a class, and have make_id
as an instance method, and have that instance as a global (if you must).
不,最好的替代方法是函数属性。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.