为什么通过分配新值会出现错误?

时间:2019-01-27 07:13:34

标签: python timer

我现在进入python并编写了一些代码。 我将变量声明为全局变量,然后在函数内部调用该变量以使其递增。但是,出现错误“分配前已引用本地变量'iTime'”

import time, threading

global iTime

def init():
    iTime=0

def foo():

    iTime+=1
    threading.Timer(1, foo).start()

init()
foo()

2 个答案:

答案 0 :(得分:0)

import React, { Component } from 'react'; import '../App.css'; import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth'; import * as firebase from 'firebase' const uiConfig = { signInFlow: 'popup', signInSuccessUrl: '/signedIn', signInOptions: [ firebase.auth.GoogleAuthProvider.PROVIDER_ID, firebase.auth.FacebookAuthProvider.PROVIDER_ID, firebase.auth.EmailAuthProvider.PROVIDER_ID, ], credentialHelper: 'none' }; export default class SignInScreen extends Component { render() { return ( <div> <h1>My App</h1> <p>Please sign-in:</p> <StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()}/> </div> ); } } 关键字用于将变量声明为超出定义变量的范围。除此之外,还必须在更改值之前将其显式声明为正在使用的每个作用域内的全局变量。这是因为使用全局变量是不好的编程习惯,因此python要确保您要在函数内部使用全局变量。为了使代码正常工作,您可以像这样更改它。

Global

答案 1 :(得分:0)

出现该错误的原因是因为iTime是在全局范围内定义的,而不是在调用它的函数中定义的。我被教导要避免使用全局变量,但是您可以通过在函数内部而不是外部使用global关键字来完成您要尝试的操作:

iTime = 0
def foo():

    global iTime
    iTime +=1
    threading.Timer(1, foo).start()

init()
foo()