Python 如何使用';更新';函数到';打开';如果对象尚未打开,是否更新?
我的例子是一个进度条 进度条最简单的形式是Python 如何使用';更新';函数到';打开';如果对象尚未打开,是否更新?,python,Python,我的例子是一个进度条 进度条最简单的形式是 bar = ProgressBar.Open() for item in list: bar.Update(count, len(list)) 我希望我的呼叫代码是 for item in list: bar.Update(count, len(list)) 我想让我的Update()函数Open()为未打开的调用者提供一个条。调用者不需要任何其他访问该条的权限,只需要更新它,因此拥有meter`handle没有任何价值 我如何保持
bar = ProgressBar.Open()
for item in list:
bar.Update(count, len(list))
我希望我的呼叫代码是
for item in list:
bar.Update(count, len(list))
我想让我的Update()
函数Open()
为未打开的调用者提供一个条。调用者不需要任何其他访问该条的权限,只需要更新它,因此拥有meter`handle没有任何价值
我如何保持状态来判断之前是否调用过更新
我可以创建一个全局变量并以这种方式跟踪,但我有一种直觉,那就是Pythonista的做法。
再试一次,但以一种不适用于绊倒的方式
基本问题是:
我有一个函数将被多次调用。
我想在它第一次被调用时做一些不同的事情。
Python中的函数如何做到这一点
在C中,这当然是一个。。。
静态变量
对不起,我刚在打字的时候弄明白了
========================
我确信所有这些编辑都不是stackoverflow应该如何工作的。很抱歉,我还没有弄好,但我非常感谢您的回复
尽管听起来我违反了所有良好实践的规则,但从打电话者的角度来看,我希望能产生影响
如果在程序中添加进度表(即使是调试)唯一需要做的事情就是在要显示进度的位置调用进度表更新,该怎么办
这就是潜在的动机。滑入单线,找些凉快的东西来解决问题
这个进度表是通过添加一个调用而添加到我原本无聊的文件去复印机中的:
msg = f'Deduplicating {idx} of {total_files} files\n' f'{dup_count} Dupes found\n' f'{small_count} Too small'
not_cancelled = sGUI.ProgressBar('De-dupe', msg, idx, total_files)
好的,我找到了一个使用“globals”的解决方案。我认为嵌套函数是实现它的方法。。。然后我把两者混合起来 我所说的“全局变量”是指在函数范围之外声明的变量。我希望能够导入我的模块,而无需导入创建任何内容 下面的代码演示了如何使用globals执行此操作
def my_update(amount):
global flag
if 'flag' in globals():
print('I have been here')
else:
print('I have not been here')
flag = True
return
for i in range(10):
print(f'Calling number {i}')
result = my_update(1)
它实现了我设定的目标,但我相信还有更好、更安全、更优雅的方法。好的,我找到了使用“全局”的解决方案。我认为嵌套函数是实现它的方法。。。然后我把两者混合起来 我所说的“全局变量”是指在函数范围之外声明的变量。我希望能够导入我的模块,而无需导入创建任何内容 下面的代码演示了如何使用globals执行此操作
def my_update(amount):
global flag
if 'flag' in globals():
print('I have been here')
else:
print('I have not been here')
flag = True
return
for i in range(10):
print(f'Calling number {i}')
result = my_update(1)
它实现了我设定的目标,但我相信还有更好、更安全、更优雅的方法。为了避免使用全局变量,可以使用decorator。下面是一个简单的例子:
def open():
print 'open'
def update():
print 'update'
def call_once(func1, *args1, **kwargs1):
def decorator(func2):
called = [False]
def wrapper(*args2 ,**kwargs2):
if not called[0]:
func1(*args1, **kwargs1)
called[0] = True
return func2(*args2, **kwargs2)
return wrapper
return decorator
@call_once(open)
def my_update():
update()
for i in xrange(5):
my_update()
结果如下:
open
update
update
update
update
update
有关decorator的更多信息,请访问:要避免使用全局变量,可以使用decorator。下面是一个简单的例子:
def open():
print 'open'
def update():
print 'update'
def call_once(func1, *args1, **kwargs1):
def decorator(func2):
called = [False]
def wrapper(*args2 ,**kwargs2):
if not called[0]:
func1(*args1, **kwargs1)
called[0] = True
return func2(*args2, **kwargs2)
return wrapper
return decorator
@call_once(open)
def my_update():
update()
for i in xrange(5):
my_update()
结果如下:
open
update
update
update
update
update
有关decorator的更多信息,请访问:要获得所需信息,可以使用类:
class ProgressBar:
def __init__(self):
self._opened = False
def Open(self):
print("Open")
def Update(self):
if self._opened:
print("Update!")
else:
self.Open()
print("set flag")
self._opened = True
print("Update")
在行动中:
In [32]: bar = ProgressBar()
In [33]: bar.Update()
Open
set flag
Update
In [34]: bar.Update()
Update!
注意:为了让您更清楚,我复制了您的大小写,但是,官方Python样式如下:
class ProgressBar:
def __init__(self):
self._opened = False
def open(self):
pass # open stuff
def update(self):
if self._opened:
pass # update stuff
else:
self.open()
self._opened = True
使用
snake\u case
进行除ClassName
之外的所有操作 为了满足您的需要,您可以使用一个类:
class ProgressBar:
def __init__(self):
self._opened = False
def Open(self):
print("Open")
def Update(self):
if self._opened:
print("Update!")
else:
self.Open()
print("set flag")
self._opened = True
print("Update")
在行动中:
In [32]: bar = ProgressBar()
In [33]: bar.Update()
Open
set flag
Update
In [34]: bar.Update()
Update!
注意:为了让您更清楚,我复制了您的大小写,但是,官方Python样式如下:
class ProgressBar:
def __init__(self):
self._opened = False
def open(self):
pass # open stuff
def update(self):
if self._opened:
pass # update stuff
else:
self.open()
self._opened = True
使用
snake\u case
进行除ClassName
之外的所有操作 我在一个Python论坛上发布了这个问题,并使用函数属性得到了迄今为止最好的答案。这是辉煌的,它的工作
下面是演示此构造的代码。。。在我看来,它应该出现在每个人的“最喜欢的Python构造”笔记本中
def func():
if not hasattr(func, 'static_variable'):
func.static_variable = 0
func.static_variable += 1
return func.static_variable
def main():
for i in range(10):
print('func = {}'.format(func()))
if __name__ == '__main__':
main()
输出是
func = 1
func = 2
func = 3
func = 4
func = 5
func = 6
func = 7
func = 8
func = 9
func = 10
我在一个Python论坛上发布了这个问题,并使用函数属性得到了迄今为止最好的答案。这是辉煌的,它的工作 下面是演示此构造的代码。。。在我看来,它应该出现在每个人的“最喜欢的Python构造”笔记本中
def func():
if not hasattr(func, 'static_variable'):
func.static_variable = 0
func.static_variable += 1
return func.static_variable
def main():
for i in range(10):
print('func = {}'.format(func()))
if __name__ == '__main__':
main()
输出是
func = 1
func = 2
func = 3
func = 4
func = 5
func = 6
func = 7
func = 8
func = 9
func = 10
使用自己的变量,如
opened=True
来控制它如果不打开进度条,bar
会是什么?什么是ProgressBar
?它是某种GUI元素吗?什么GUI?如果不是self.opened:self.Open()
?@MikeyB因此,在Bar
类中添加一个内部标志self.opened
,然后在def Update(self)中使用该检查如果self.opened:
:
使用自己的变量,如opened=True
来控制它如果不打开进度条,bar
会是什么?什么是ProgressBar
?它是某种GUI元素吗?什么GUI?如果不是self.opened:self.Open()
?@MikeyB所以,在你的Bar
类中添加一个内部标志self.opened
,然后,在def Update(self):
Oh crap,你说得对。。。我不需要那个嵌套函数。《环球时报》自有其用武之地。是的,但不要这样做。使用类来封装状态。这就是OOP的作用。你能告诉我如何用一段代码做到这一点吗?哦,糟了,你说得对。。。我不需要那个嵌套函数。《环球时报》自有其用武之地。是的,但不要这样做。使用类来封装状态。这就是OOP的用途。你能给我演示一下如何用一段代码做到这一点吗?啊!这就是我所希望的!非常感谢你。当然,关于Python我还有很多东西要学。Python有很多深度,在第一次使用时很容易忽略。啊!这就是我所希望的!非常感谢你。当然,关于Python我还有很多东西要学。Python有很多深度,在第一次使用时很容易忽略。@MikeyB这就是我的意思,对,是的。但是此解决方案使用两个