0
点赞
收藏
分享

微信扫一扫

定义函数的参数 nameerror

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 的定义时就定义,只需要在执行时定义即可。

举报

相关推荐

0 条评论