[英]Python best practices for functions
方法1(全局变量):
id_constant = 1000
id_cnt = 1
def give_id():
global id_cnt
id_cnt += 1
return id_constant * id_cnt
id = give_id()
方法2(fuc var而不是global var):
id_cnt = 1
def give_id():
id_constant = 1000
global id_cnt
id_cnt += 1
return id_constant * id_cnt
id = give_id()
方法3(通过全球大战):
id_cnt = 1
id_constant = 1000
def give_id(constant, cnt):
return constant * cnt
global id_cnt
id_cnt +=1
id = give_id(id_constant, id_cnt)
我不确定是否有任何一般的经验法则但是被广泛接受的函数来访问函数内的全局变量? 或者如果变量仅用于函数,那么它应该是函数变量的一部分吗?
该方法通常取决于具体情况。
你似乎需要独特的ID,为什么不使用发电机 :
def create_id_generator():
"""Returns an id generator."""
i = 0
while True:
yield i
i += 1
与next()
函数一起使用:
>>> ID_GENERATOR = create_id_generator() # Global variable
>>> my_id = next(ID_GENERATOR)
>>> my_id2 = next(ID_GENERATOR)
>>> my_id3 = next(ID_GENERATOR)
>>> print(my_id, my_id2, my_id3, next(ID_GENERATOR))
0 1 2 3
如果希望id为1000
倍数,可以通过参数将常量传递给生成器:
def create_id_generator(multiplier=1000):
"""Returns an id generator."""
i = 0
while True:
yield i * multiplier
i += 1
如果您不想从索引0开始,甚至可以添加起始值:
def create_id_generator(multiplier=1000, start_index=0):
"""Returns an id generator."""
while True:
yield start_index * multiplier
start_index += 1
如果id_constant
实际上是常量 ,我会做到:
ID_CONSTANT = 1000
def give_id(id_count):
return ID_CONSTANT * id_count
id_count = 1
id = give_id(id_count)
但看起来你也有一些状态( id_count
)需要与id
的发布保持id_count
,这表明了一个生成器函数:
def give_id(id_count):
while True:
yield ID_CONSTANT * id_count
id_count += 1
甚至是一堂课:
class IdCreator(object):
ID_CONSTANT = 1000
def __init__(self, start_count=1):
self.id_count = start_count
def give_id(self):
new_id = self.ID_CONSTANT * self.id_count
self.id_count += 1
return new_id
来自Python的禅宗(即import this
)
Namespaces are one honking great idea -- let's do more of those!
一般来说,如果你不需要在全局命名空间中放置一些东西,最好将它封装在函数的本地命名空间中,所以我认为选项2更加“ id_constant
”,除非将使用id_constant
通过多种功能。
您也可以使用带有默认值的关键字参数尝试以下操作:
id_cnt = 1
def give_id(id_constant=1000):
global id_cnt
id_cnt += 1
return id_constant * id_cnt
id = give_id()
然后,如果你需要id_constant是不同的东西,你可以将函数调用为id = give_id(id_constant = 500)。
全局变量通常是您应该避免的。
如果你想拥有常量,比方说,配置目的,我会采取更多的模块方法,如:
conf.py
MYCONST = 1000
app.py
import conf
print conf.MYCONST
或者采取OO方法,例如:
class Test(object):
def __init__(self):
self._constant = 1000
def give_id(self, cnt):
return self._constant * cnt
可能你需要发电机功能?
def give_id(id_constant):
delta = 0
while True:
delta += 1
yield id_constant + delta
for i in range(100):
print(give_id(1000)) # prints numbers from 1001 to 1100
一点棘手的东西:
def get_id_func(constant):
class c(object):
def __init__(self, constant):
self.constant = constant
self.id = 0
def func(self):
self.id += 1
return self.id * self.constant
o = c(constant)
return o.func
# create function
f = get_id_func(1000)
# call and test it
assert f() == 1000
assert f() == 2000
assert f() == 3000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.