我试图将一个变量从一个函数传递给一个类.示例代码如下:
def hello(var):
return var
class test():
def __init__(self):
pass
def value(self):
print var
hello(var)
test = test()
test.value()
Run Code Online (Sandbox Code Playgroud)
我想var进入课堂test().
谢谢你的帮助.
我在代码的开头有这个变量:
enterActive = False
Run Code Online (Sandbox Code Playgroud)
然后,在最后,我有这个部分:
def onKeyboardEvent(event):
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
if enterActive == True:
m_lclick()
return True
hookManager.KeyDown = onKeyboardEvent
hookManager.HookKeyboard()
pythoncom.PumpMessages()
Run Code Online (Sandbox Code Playgroud)
当我先按Enter键然后先按F2键时出现此错误:
UnboundLocalError: local variable 'enterActive' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
我知道为什么会这样,但我不知道怎么解决它...
任何人?
我运行此脚本时出现错误(标题中显示):
import psycopg2
conn = None
conn_string = "host='localhost' dbname='localdb' user='someuser' password='abracadabra'"
def connectDb():
if conn is not None: # Error occurs on this line
return
# print the connection string we will use to connect
print "Connecting to database\n ->%s" % (conn_string)
Run Code Online (Sandbox Code Playgroud)
conn具有全局范围,并且在函数中引用之前被赋值为None - 为什么出现错误消息?
我刚刚开始学习python并不断得到一个我无法弄清楚的错误.任何帮助都将受到大力赞赏.基本上,我不断收到以下错误:
Enter an int: 8
Traceback (most recent call last):
File "C:\Users\Samuel\Documents\Python Stuff\Find Prime Factors of Number.py", line 16, in <module>
once_cycle()
File "C:\Users\Samuel\Documents\Python Stuff\Find Prime Factors of Number.py", line 8, in once_cycle
while x==0:
UnboundLocalError: local variable 'x' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
我看到很多人都有同样的问题,但当我看到人们告诉他们要做的事情时,我无法理解.无论如何,我的代码是这样的.我已经重新检查了所有缩进,并且看不出它的问题.这个程序的目的是找到一个int的主要因素(虽然它只有90%完成).它是用Python 2.7.3编写的.
import math
testedInt = float(raw_input("Enter an int: "))
workingInt = testedInt
x = 0
def once_cycle():
for dividor in range(1, int(math.floor(math.sqrt(testedInt))+1)):
while x==0:
print "Called"
if (workingInt%dividor == 0):
workingInt = workingInt/dividor
x = 1
if …Run Code Online (Sandbox Code Playgroud) 这是我模块的完整代码,名为util.py:
import my_other_module
__IMPORTANT_OBJECT__ = None
def getImportantObject():
if __IMPORTANT_OBJECT__ is None:
__IMPORTANT_OBJECT__ = my_other_module.ImportantObject()
return __IMPORTANT_OBJECT__
Run Code Online (Sandbox Code Playgroud)
我的理解是,前缀为双下划线的变量被认为是模块的私有变量.这里的想法是,我想存储对重要对象的私有引用,并将其返回给通过该getImportantObject()方法请求它的任何人.但我不希望在第一次调用此方法之前启动该对象.
但是,当我运行我的代码时,我收到以下错误:
File "/Users/Jon/dev/util.py", line 6, in getImportantObject
if __IMPORTANT_OBJECT__ is None:
UnboundLocalError: local variable '__IMPORTANT_OBJECT__' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
什么是完成我在这里尝试做的推荐方法?
如何在python中定义全局数组我想将tm和prs定义为全局数组,并在两个函数中使用它们,如何定义它们?
import numpy as np
import matplotlib.pyplot as plt
tm = []
prs = []
def drw_prs_tm(msg):
tm = np.append(tm,t)
prs = np.append(prs,s)
def print_end(msg):
plt.plot(tm,prs,'k-')
Run Code Online (Sandbox Code Playgroud) 我需要在"主程序"中将类方法中创建的值传递给函数,过程或def或其调用的任何内容.
global myValue
class CalcFrame(object):
def clearFunc(self):
myValue = 12
def getUrl():
print myValue
Run Code Online (Sandbox Code Playgroud)
这是我的想法,显然它不起作用:
我做那个代码,然后我创建一个对象
x = CalcFrame()
Run Code Online (Sandbox Code Playgroud)
调用应该设置全局的方法
x.clearFunc()
Run Code Online (Sandbox Code Playgroud)
然后调用应该打印它的函数
getUrl()
Run Code Online (Sandbox Code Playgroud)
得到错误
NameError:未定义全局名称"myValue"
我在python中将多个变量调用到另一个函数时遇到一个小问题.就像我必须在yyy()中访问xxx()变量的变量一样.帮我这样做.?
示例:
def xxx():
a=10
b=15
c=20
def yyy():
xxx()
print a ### value a from xxx()
print b ### value b from xxx()
yyy()
Run Code Online (Sandbox Code Playgroud) 我坚持在另一个函数中使用在前一个函数中定义的变量。例如,我有这个代码:
def get_two_nums():
...
...
op = ...
num1 = ...
num2 = ...
answer = ...
def question():
response = int(input("What is {} {} {}? ".format(num1, op, num2)))
if response == answer:
.....
Run Code Online (Sandbox Code Playgroud)
我将如何在第二个函数中使用第一个函数中定义的变量?先感谢您
我有一个功能 load
def load():
file = open((input("File name: ")), "r")
movies_list = file.readlines()
movies_list = [movie.strip() for movie in movies_list]
file.close()
Run Code Online (Sandbox Code Playgroud)
我想movies_list在另一个函数中使用该列表randomSelection
def randomSelection():
print(random.choice(movies_list))
Run Code Online (Sandbox Code Playgroud)
我怎么能绕过这个?有没有办法声明movies_list为全局变量?
这可能很荒谬,但我无法理解在 Python 中使用全局变量。它给我抛出了使用关键字的语法错误
global
Run Code Online (Sandbox Code Playgroud)
尽管如此,我在文档中确实是这样查找的。
我知道代码由于重复使用全局变量而显得笨拙。无论如何,如何正确使用它们?
import random
r_list = []
my_list =[3,4,45,7,23,33]
match_list=[]
iteration = 0
number_matches = 0
def fill_random_list():
for i in range(7):
# print (random.randint(1,49))
r_list.append(random.randint(1,49))
def return_matches(lista, listb):
# print set(lista).intersection(listb)
return set(lista).intersection(listb)
def return_number_matches(l_matches):
if l_matches:
return len(l_matches)
def draw_lottery():
while global number_matches < 5:'''
File "C:/Lottery.py", line 27
while global number_matches < 5:
^
SyntaxError: invalid syntax'''
global r_list = []
global match_list = []
fill_random_list()
match_list=return_matches(r_list, my_list)
global number_matches=(return_number_matches(global match_list))
global iteration+=1 …Run Code Online (Sandbox Code Playgroud) 我已将变量fiblist声明为全局变量,但它在gen10fib中获得None的值.
# Enter your code here. Read input from STDIN. Print output to STDOUT
#program to check if a number is fibonacci number
global fiblist
fiblist=[0,1] #list to store generated fibonacci numbers
global Nlist
Nlist=[] # list for T test cases
global solnList
solnList=[] #contains the solution 1 is fibo 0 not fibo
global head
head=1 #to denote the maximum element in the list
def comparator(fiblist,x,head):
if(head<x):
gen10fib(fiblist) #generates the next 10 numbers of fibonacci sequence and appends them to …Run Code Online (Sandbox Code Playgroud) 使用以下示例代码:
mat = []
x = 5
def add(c,b):
print c+b
x = 8
mat.append(c)
mat.append(b)
add(5,6)
add(8,9)
print mat
print x
Run Code Online (Sandbox Code Playgroud)
mat是附加但为什么不是x改变?为什么python以不同的方式处理列表和变量?