首页 > 编程知识 正文

python中全局变量和局部变量,python中定义全局变量

时间:2023-05-06 10:41:22 阅读:144906 作者:1851

iamusingalistonwhichsomefunctionsworksinmyprogram.thisisasharedlistactuallyandallofmyfunctionscaneditit.isitreallynecessararation

imeanputtingtheglobalkeywordbehinditineachfunctionthatusesit,ordefiningitoutsideofallthefunctionsisenoughwithoutusingtheglobobeglobusit

whenyouassignavariable(x=. )、 youarecreatingavariableinthecurrentscope (e.g.localtothecurrentfunction ).ifithappenstoshadowavariablefronanouter ).e ) ) scope,welltoobad-python doesn ' TC are (and that ' sagoodthing ).So you can't do this:

x=0

杰夫(: )

x=1

f () ) )

打印x #=0

and expect 1. Instead,youneeddodeclarethatyouintendtousetheglobalx :

x=0

杰夫(: )

全局x

x=1

f () ) )

打印x #=1

utnotethatassignmentofavariableisverydifferentfrommethodcalls.youcanalwayscallmethodsonanythinginscope-e.g.onvariariabler

alsoveryimportant 3360 member assignment (x.name=. ),itemassignment ) collection[key]=.sliceassignment ) sliciciction andthereforeyoudon ' tneedglobaltochangeaglobal ' smembersorcallitmethods (evenwhentheymutatetheobject )。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。