我是一个python /编程新手,也许我的问题根本就没有意义.
我的问题是,如果变量是动态的,我无法将变量变为全局变量,我的意思是我可以这样做:
def creatingShotInstance():
import movieClass
BrokenCristals = movieClass.shot()
global BrokenCristals #here I declare BrokenCristals like a global variable and it works, I have access to this variable (that is a shot class instance) from any part of my script.
BrokenCristals.set_name('BrokenCristals')
BrokenCristals.set_description('Both characters goes through a big glass\nand break it')
BrokenCristals.set_length(500)
Fight._shots.append(BrokenCristals)
def accesingShotInstance():
import movieClass
return BrokenCristals.get_name()#it returns me 'BrokenCristals'
Run Code Online (Sandbox Code Playgroud)
但如果不这样做,我声明一个像这样的字符串变量:
def creatingShotInstance():
import movieClass
a = 'BrokenCristals'
vars()[a] = movieClass.shot()
global a #this line is the only …Run Code Online (Sandbox Code Playgroud) 根据python reference manual我们有
如果根本找不到名称,则会引发 NameError 异常。如果名称引用尚未绑定的局部变量,则会引发 UnboundLocalError 异常。UnboundLocalError 是 NameError 的子类。
我不明白什么时候UnboundLocalError抛出?因为
Python 缺少声明并允许名称绑定操作发生在代码块中的任何位置。
那么我们如何才能声明一个变量,而不去初始化她呢?
我编写了一个基本的绘图破折号应用程序,它从 csv 中提取数据并将其显示在图表上。然后,您可以在应用程序上切换值并更新图表。
但是,当我向 csv 添加新数据(每天一次)时,应用程序不会在刷新页面时更新数据。
解决方法通常是将您定义app.layout为一个函数,如此处所述(向下滚动到页面加载时的更新)。您将在下面的代码中看到我已经做到了这一点。
这是我的代码:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
path = 'https://raw.githubusercontent.com/tbuckworth/Public/master/CSVTest.csv'
df = pd.read_csv(path)
df2 = df[(df.Map==df.Map)]
def layout_function():
df = pd.read_csv(path)
df2 = df[(df.Map==df.Map)]
available_strats = np.append('ALL',pd.unique(df2.Map.sort_values()))
classes1 = pd.unique(df2["class"].sort_values())
metrics1 = pd.unique(df2.metric.sort_values())
return html.Div([
html.Div([
dcc.Dropdown(
id="Strategy",
options=[{"label":i,"value":i} for i in available_strats],
value=list(available_strats[0:1]),
multi=True …Run Code Online (Sandbox Code Playgroud) 我一直在阅读Python教科书,我看到以下代码:
class Database:
# the database implementation
pass
database = None
def initialize_database():
global database
database = Database()
Run Code Online (Sandbox Code Playgroud)
现在,为什么函数global内部有声明initialize_database?我们已经定义database了函数外部,它不是已经全局化了吗?
最好的祝福,
我假设你们很多人都熟悉CodeAcademy Python类.正如标题所说,我必须得到全班的平均分.这就是我所做的:
def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)
Run Code Online (Sandbox Code Playgroud)
我得到的错误是"哎呀,再试一次.get_class_average([alice,lloyd])按预期返回91.15而不是85.85".我现在似乎无法找到我的错误5个小时,所以请看一看并告诉我代码有什么问题.
我想更好地理解python中的作用域.我有以下玩具示例:
a = 1
print "in global: " + str(a)
def g():
a += 1
print "in g(): " + str(a)
def f():
a += 1
print "in f(): " + str(a)
g()
f()
Run Code Online (Sandbox Code Playgroud)
我希望这会运行并打印出来1然后2再打印出来2.但是,我得到了错误:
UnboundLocalError: local variable 'a' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
我会想到两者g()并且f()会a从全球范围中拉出来.不正确的?
更新:感谢您的答案,但不清楚的是:如果我只想读取全局变量a并将其分配给我创建的局部变量,还可以命名a吗?
我这样做的原因是我试图找出是否g()继承了f()调用它的范围或者定义它的全局范围?
这篇文章已经回复,如果你愿意,请阅读.
我一直在尝试在python 3中编写一个卡片游戏,我一直在使用for循环将牌从牌组列表转移到手牌列表.我试图将它放入一个函数,但命令提示符崩溃.救命?
from random import *
print("Sam's Casino")
cards = ['1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K']
shuffle(cards)
print(cards)
hand1 = []
hand2 = []
count = 0
def deal(cards):
for card in cards:
if count < 4:
hand1.append(card)
count += 1
if count > 3 and count < 8:
hand2.append(card)
count += 1
deal(cards)
print(hand1)
print(hand2)
input('>')
Run Code Online (Sandbox Code Playgroud)
编辑:没有收到任何错误,它只是关闭.
我编写了几个函数来计算样本响应的 NPS 和误差幅度。
我不想从第一个函数返回结果,然后将它传递给另一个函数以便能够使用它们。
所以我希望创建全局变量,这些变量可以在它创建的函数之外使用,以便它可以在其他函数中使用而无需传递它们。
但它似乎抛出错误。知道如何实现这一目标吗?我不想使用类并将这些变量作为类变量。
def nps_score(responses):
"""Function to get the NPS score from the
Survey responses
"""
global sample_size = len(responses)
global promoters_proportion = sum([1 for x in responses if x >=9])/sample_size
global detractors_proprotion= sum([1 for x in responses if x<=6])/sample_size
global sample_NPS= promoters_proportion - detractors_proportion
print("Sample Net Promoter Score(NPS) is {} or {}%".format(sample_NPS,sample_NPS*100))
def moe():
""" Calculate the margin of error
of the sample NPS
"""
# variance/standard deviation of the sample NPS using
# Discrete random …Run Code Online (Sandbox Code Playgroud) 这是我的代码:
import time
GLO = time.time()
def Test():
print GLO
temp = time.time();
print temp
GLO = temp
Test()
Run Code Online (Sandbox Code Playgroud)
回溯(最近一次调用最后一次):文件“test.py”,第 11 行,在 Test() 文件“test.py”,第 6 行,在测试打印 GLO UnboundLocalError:分配之前引用的局部变量“GLO”
添加时出现错误GLO = temp,如果注释掉,函数就可以成功执行,为什么?
我该如何设置GLO = temp?
我已经开始自学python,并且注意到与全局变量和范围有关的某些奇怪事情。当我运行这个:
x = 2
y = 3
z=17
def add_nums():
y = 6
return z+y
Run Code Online (Sandbox Code Playgroud)
打印结果为23 ...但是,当我将返回值扩展为:
x = 2
y = 3
z=17
def add_nums():
y = 6
z = z + y
return z
Run Code Online (Sandbox Code Playgroud)
我在第6行收到以下错误:
Local name referenced but not bound to a value.
A local name was used before it was created. You need to define the
method or variable before you try to use it.
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么我在这里遇到错误,因为z是全局可访问的。
python ×10
variables ×2
declaration ×1
function ×1
jes ×1
namespaces ×1
plotly-dash ×1
python-2.7 ×1
python-2.x ×1
python-3.x ×1
scope ×1