NameError Traceback (most recent call last) Cell In[5], line 8 6 global VAL 7 VAL = self.val ----> 8 def myfun(val=VAL): 9 print(val)
NameError: name 'VAL' is not defined
class MyClass():
def __init__(self):
self.val = "val"
self.read()
def read(self):
global VAL
VAL = self.val
def myfun(val=VAL):
print(val)
The error you're seeing is because the global variable VAL
is not defined at the time of defining the function myfun
. In Python, default argument values are evaluated at the point of function definition in the defining scope. So at the time of defining myfun
, VAL
is not yet defined.
Here's a corrected version of your code:
class MyClass():
def __init__(self):
self.val = "val"
self.read()
def read(self):
global VAL
VAL = self.val
def myfun(val=None):
if val is None:
global VAL
val = VAL
print(val)
In this version, myfun
takes an argument val
which defaults to None
. If None
is passed to the function (or no argument is passed), it will use the global VAL
as its value. This way, VAL
doesn't need to be defined at the time of myfun
's definition, only at the time of its execution.
你看到的错误是因为在定义函数 myfun
时,全局变量 VAL
还未定义。在 Python 中,函数的默认参数值是在函数定义时在定义作用域中进行求值的。所以在定义 myfun
时,VAL
还未定义。
以下是你的代码的修正版本:
class MyClass():
def __init__(self):
self.val = "val"
self.read()
def read(self):
global VAL
VAL = self.val
def myfun(val=None):
if val is None:
global VAL
val = VAL
print(val)
在这个版本中,myfun
接受一个默认为 None
的参数 val
。如果传递给函数的是 None
(或者没有传递参数),它将使用全局的 VAL
作为其值。这样,VAL
不需要在 myfun
的定义时就定义,只需要在执行时定义即可。
上面的代码还是错的 实际上是
class MyClass():
def __init__(self):
self.val = "val"
self.read()
def read(self):
global VAL
VAL = self.val
def myfun(val=None):
# https://blog.51cto.com/u_16055028/8648140
if not val:
MyClass() # 或放在myfun定义代码块之前, 任意处均可
val = VAL
print(val)
myfun()
# 其实应该写var
或者
class MyClass():
def __init__(self):
self.val = "val"
self.read()
def read(self):
global VAL
VAL = self.val
def myfun(val=None):
if val is None:
global VAL
val = VAL
print(val)
# 创建 MyClass 的实例
my_class = MyClass()
# 现在可以调用 myfun() 了
myfun()
或者
class MyClass():
def __init__(self, val="val"):
self.val = val
def set_global(self):
global VAL
VAL = self.val
def myfun(val=None):
if val is None:
global VAL
val = VAL
print(val)
# 创建 MyClass 的实例
my_class = MyClass()
# 设置全局变量 VAL
my_class.set_global()
# 现在可以调用 myfun() 了
myfun()