如何在内部函数中获取外部函数变量?

2024-10-01 07:37:36 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码不打印任何内容:

class Special:
    def __init__(self, New_ced_file):
        self.new_ced_file = new_ced_file
    
    def compareParameter(self):
        Input = pd.read_csv(new_ced_file, low_memory=False)
        MG = pd.DataFrame({RF1: [1,2,3], 'RD2: '[4,5,6]})
        def MG_data():
            for i, j in Input.iterrows():
                print (j) **#it does not print anything** 
                for k,l in MG.iterrows():
                    print (l) **#it does not print anything** 
    
    new_ced_file = os.path.realpath('///') #filepath
    myobject = Special(new_ced_file)
    myobject.compareParameter()

如何将外部函数变量调用为内部函数


Tags: inselfnewforinputdefitfile
3条回答

您可以从外部函数调用内部函数,并将变量传递给内部函数:

class Special:
  def __init__(self, New_ced_file):
    self.new_ced_file = new_ced_file

  def compareParameter(self):
    Input = pd.read_csv(new_ced_file, low_memory=False)
    MG = pd.DataFrame({'RF1': [1,2,3], 'RD2: '[4,5,6]})
    def MG_data(Input, MG):
        for i, j in Input.iterrows():
            print(j)
            for k,l in MG.iterrows():
                print(l)
    result = MG_data(Input, MG) 

new_ced_file = (r'\\\') #filepath
myobject = Special(new_ced_file)
myobject.CompareParameter()

此外,如果您在字符串中使用\,请执行以下操作之一:

  • 在字符串前面添加一个r:r'\'
  • 或者使用另一个反斜杠取消反斜杠:'\\'(变成一个反斜杠)

您应该使用nonlocal关键字在内部函数中使用外部函数变量

class Special:
  def __init__(self, New_ced_file):
    self.new_ced_file = new_ced_file

  def compareParameter(self):
    Input = pd.read_csv(new_ced_file, low_memory=False)
    MG = pd.DataFrame({'RF1': [1,2,3], 'RD2: '[4,5,6]})
    def MG_data():
        nonlocal Input, MG
        for i, j in Input.iterrows():
            print(j)
            for k,l in MG.iterrows():
                print(l)

new_ced_file = (r'\\\') #filepath
myobject = Special(new_ced_file)
myobject.CompareParameter()

您的代码中存在各种类型的输入错误,这将导致错误或意外行为

我无法想象您的代码是否正常工作,因此请在问题中包含您遇到的任何错误,以便我们可以更有效地帮助您

  • __init__两边应该有两个下划线
  • __init__调用的New_ced_file参数应与方法中使用的变量匹配
  • Input与不推荐使用的内置{}非常相似
  • compareParameter中引用new_ced_file,但应使用self.new_ced_file
  • RF1应该被引用:'RF1'
  • 分配给result不会起任何作用,请改用return MG_data(Input, MG)
  • 此外,如果在字符串中使用\,则可以:
    • 在字符串前面添加一个r:r'\'
    • 或者使用另一个反斜杠取消反斜杠:'\\'(变成一个反斜杠)

相关问题 更多 >