繁体   English   中英

当类在函数中时,为什么类中的全局行为会有所不同?

[英]why does global in a class behave differently when the class is within a function?

我正在尝试使用ginput来注册地图上的点击,并想使用 matplotlib 小部件添加操作按钮。 在下面的代码中,我可以通过将 action 的值声明为global来将其传递回主代码。 如果我点击地图,action=0,如果我点击按钮,action=1,根据需要。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

class Index:
    def test(self, event):
        global action
        action=1

# fake data
x=np.arange(30)
y=x**2
fig,ax=plt.subplots()
ax.plot(x,y)
callback = Index()
buttonname=['test']
colors=['white']
idx=[0.2]
bax,buttons={},{}

# set up list of buttons.
for i,col,button in zip(idx,colors,buttonname):
    bax[button] = plt.axes([0.92, i, 0.07, 0.07])
    buttons[button] = Button(bax[button],button,color=col,hovercolor='green')
    buttons[button].on_clicked(getattr(callback,button))

# register click on plot
while True:
     pts=plt.ginput(1)
     plt.pause(0.5)
     print("action is ",action)
     action=0 # reset 

但我的困惑是,如果我采用完全相同的代码并将其放在 def 块中,则 action 的值不再传回, action始终为零。

def subtest():
    class Index:
        def test(self, event):
            global action
            action=1

    # fake data
    action=0
    x=np.arange(30)
    y=x**2
    fig,ax=plt.subplots()
    ax.plot(x,y)
    callback = Index()
    buttonname=['test']
    colors=['white']
    idx=[0.2]
    bax,buttons={},{}

    # set up list of buttons.
    for i,col,button in zip(idx,colors,buttonname):
        bax[button] = plt.axes([0.92, i, 0.07, 0.07])
        buttons[button] = Button(bax[button],button,color=col,hovercolor='green')
        buttons[button].on_clicked(getattr(callback,button))

    # register click on plot
    while True:
         pts=plt.ginput(1)
         plt.pause(0.5)
         print("action is ",action)
         action=0 # reset

res=subtest()

我很困惑为什么会发生这种情况。 我尝试将类定义移到主代码中,但这没有帮助。 我对任何类型的解决方案都感到高兴(例如,通过参数传递动作,我不知道如何处理小部件),因为我认为使用global经常会皱眉。 但基于global的解决方案也很好。

action里面subtest是本地的子测试,而action里面Index.test是全球性的。 无论是声明action在全球subtest ,或者使用nonlocalIndex.test

(我怀疑没有全局变量可能有更好的解决方案,但由于我不熟悉 GUI 工具包,我将把它留给其他人。)

你想看看这篇关于闭包的文章和这篇关于闭包的另一篇文章 我认为您需要在类和函数之外声明 action,然后在类中使用 global 引用它。

我不认为你需要使用一个类——你可以绕过函数传递变量、布尔值、字典并实现同样的目的。

您可以使用“on_click”事件来执行您想要的操作,请参阅此小部件教程小部件教程matplotlib 事件处理

这是一个使用“全局”来影响状态更改的示例代码。 最好传递一个变量或使用事件来触发您希望状态影响的任何内容。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

state = False

def change_state(btn_action):
    #do something
    btn_action= not(btn_action)
    return btn_action

def grid(val):
    global state
    #do something
    state =change_state(state)
    print(state)

    ax.grid()
    fig.canvas.draw()

    #reset value
    state =change_state(state)
    print(f'resetting state to {state}')

# fake data
x=np.arange(30)
y=x**2

#create fig, ax
fig =plt.figure()
ax= fig.subplots()
p, = ax.plot(x,y)

# set up list of buttons.

buttonname=['test']
colors=['white']
idx=[0.2]
bax,buttons={},{}

for i,col,button in zip(idx,colors,buttonname):
    bax[button] = plt.axes([0.92, i, 0.07, 0.07])
    buttons[button] = Button(bax[button],button,color=col,hovercolor='green')
    buttons[button].on_clicked(grid)

#show plot
fig.canvas.draw()
plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM