调用同一类中的另一个方法时出现 Python 错误“NameError: global name 'self' is not defined”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3625726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:59:22  来源:igfitidea点击:

Python error "NameError: global name 'self' is not defined" when calling another method in same class

pythonclass

提问by Lior

I get a weird error:

我收到一个奇怪的错误:

Traceback (most recent call last):
File "/remote/us01home15/ldagan/python/add_parallel_definition.py", line 36, in <module>
new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 70, in add_parallel_extention
new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 52, in gen_parallel_hierarchy
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
NameError: global name 'self' is not defined

From all the tutorials that I have seen, calling a different method from the same class is via self.method_name

从我看过的所有教程来看,从同一个类调用不同的方法是通过 self.method_name

It's a script instantiating a class. The script is:

这是一个实例化一个类的脚本。脚本是:

#!/depot/Python-3.1.1/bin/python3.1
#gets a netlist and a cell name.
#generates a new netlist with the parallel instanciation
import sys
import re
from operator import itemgetter

sys.path.append('/remote/us01home15/ldagan/python/')
from hspice_netlist import hspice_netlist
command="" # initializing argument string
for l in sys.argv:
    command=command + " " + "".join(l)
print (len(sys.argv))
print (command)
if (len(sys.argv) <4):
    sys.exit("Pleas input original file name & new file name")

orig_netlist=hspice_netlist("file=" +  "".join(sys.argv[1])) #reading new netlist
new_netlist=hspice_netlist("") #empty netlist
match=re.search(r"subckt\s*=\s*(\S+)",command)
if (match):
    cell_name=match.group(1) #cell to be parallelized name
else:
    sys.exit("Please input subckt= <subckt name>")
match=re.search(r"level\s*=\s*(\S+)",command)
if (match):
    level=match.group(1) #levels of netlist name
else:
    sys.exit("Please input level=<level name>")
match=re.search(r"parallel\s*=\s*(\S+)",command)
if (match):
    parallel=match.group(1) #new netlist name
else:
    sys.exit("Please input parallel=<parallel name>")

new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
match=re.search(r"outfile\s*=\s*(\S+)",command)
if (match):
    output_filename=match.group[1]

outfile=open(output_filename,'w')
outfile.write("".join(new_netlist.lines))

The class code is:

类代码是:

import sys
import re
from collections import defaultdict
class hspice_netlist:
    def __init__(self,cmd):
        cmd_match=re.search(r"file\s*=\s*(\S+)",cmd)
        if (cmd_match):
            filename=cmd_match.group(1)
            self.infile = open(filename, 'r')
            self.lines=self.infile.readlines() #reading the lines
            self.infile.close() #closing filehandle

    def input_lines(self,lines):
                self.lines=lines

    def get_subckt_lines(self,name):
        gotit=0
        ret_lines=[]
        find_sub=re.compile("^.sub\S*\s+"+name, re.IGNORECASE)
        find_end=re.compile('^.ends', re.IGNORECASE)
        for line in self.lines:
            if (not gotit):
                if (find_sub.search(line)):
                    gotit=1
                    ret_lines.append(line)
                else:
                    ret_lines.append(line)
                    if (find_end.search(line)):
                        return ret_lines
        sys.exit("Could not find the lines for circuit " + name + '\n')

    def gen_parallel_inst(num,cell_1st_line):
        ret_lines=[] #starting a fresh!!
        cell_data=re.search(r"^\S+\s+(\S+)(\s+.*)", cell_1st_line)
        cell_name=cell_data.group(1) # got the cell name
        new_cell_name=cell_name + '__' + str(num) # new cell name
        nodes=cell_data.group(2) # interface
        ret_lines.append("".join([".sub ", new_cell_name,nodes,"\n"]))
        iter=num
        if (not (re.search(r"\s+$",nodes))):
            nodes=nodes + ' ' #need a space before the cell name, add if it doesn't exist
        while(iter > 0):
            line="x" + str(iter) + nodes  + cell_name + "\n"
            ret_lines.append(line)
            iter=iter-1
        ret_lines.append(".ends\n") #end of subcircuit definition
        return return_lines

    def gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):
        '''What that it does: Gets a cell name, then finds that cell's interface definition. It then simply relicates the cell, in parallel, then into hierarchies, ending with new cells' definitions. It is useful  for the HSPICE BA issue. It runs recusively. Currently it supports 1 line for interface definition, and no parameters for the cell @ this time '''
        ret_lines=[]
        cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
        ret_lines.extend(cell_lines)
        if (level>0):
            ret_lines.extend(self.gen_parallel_hierarchy(num_of_parallel,level-1,cell_lines[0]))
        return ret_lines



    def add_parallel_extention(self,cell_name,num,level):
        ''' Get a cell name + definitions and generates a new netlist '''
        i=0
        regi=re.compile("^.sub\S*\s+" + cell_name)
        m=-1
        while ( (i+1 < len(self.lines)) &  ( not m )):
            i=i+1
            m=regi.search(lines[i]) #finding the line
        if (not m):
            sys.exit("could not find subcircuit definition of " + cell_name + "\n")
        new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
        i=i-1
        ret_lines=self.lines[0:i] # creating return variable, using extend for performance
        ret_lines.extend(new_cells_definition)
        ret_lines.extend(self.lines[i+1:len(self.lines)])
        return ret_lines

        #get the cell
        #write the level 

I am definitely doing something fundamentally wrong, but I don't know what. Thanks for helping an EE newbe (to Python).

我肯定在做一些根本错误的事情,但我不知道是什么。感谢您帮助 EE 新手(到 Python)。

回答by Vinko Vrsalovic

You are missing self in two method declarations.

您在两个方法声明中缺少 self 。

These

这些

def gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):
def gen_parallel_inst(num,cell_1st_line):

should be

应该

def gen_parallel_hierarchy(self,num_of_parallel,level,cell_1st_line):
def gen_parallel_inst(self,num,cell_1st_line):

The error happens because you haven't put the self parameter in gen_parallel_hierarchy()but are referring to it in the line which fails:

发生错误是因为您没有将 self 参数放入gen_parallel_hierarchy()但在失败的行中引用它:

cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)