0

我试图将我的模块分成几个模块,以便每个模块只包含一个类。

ClassA是我的超类 in file1.pyClassB位于file2.py并继承自ClassAClassCfile3.py并且file4.py包含ClassD,继承自ClassB__main__

当我运行时,file4.py我得到以下回溯:

NameError                                 Traceback (most recent call last)
C:\Users\User\Documents\Python\file4.py in <module>()
   1016     t0 = time.time()
   1017     # Initialize dataframe object to save/export at the end of ClassD.
-> 1018     myData = ClassA(dataframe)
   1019
   1020     # Initialize ClassC objects.

C:\Users\User\Documents\Python\file1.py in __init__(self, dataframe)
     24                 self.df.rename(columns = {'%s'%header:'GTIN1'}, inplace = True)
     25             if re.search(".MPN", headerID):
---> 26                 header = headerID
     27                 self.df.rename(columns = {'%s'%header:'MPN'}, inplace = True)
     28

NameError: global name 're' is not defined

在阅读了这个问题后,我import re在这两个ClassA__init__第一行都试过了。每个文件还从目录中的其他模块导入类。我也尝试过复制到目录。这是解决方案吗?我尝试将当前目录添加到每个模块中,但这也不起作用。file1.pyre.pycsys.path

更新

下面是评论中提到的仍然返回 NameError 的代码。

import re as re, pandas as pd

from file2 import ClassB as ClassB
from file3 import ClassC as ClassC # ClassC contains static methods that use re
from file4 import ClassD as ClassD

class ClassA(object):
    """Converts dataframe from unicode string objects to Python
    string objects, renames column headers.
    """

    def __init__(self, dataframe): # dataframe is defined in file4.py in __main__
        super(ClassA, self).__init__()
        self.df = dataframe.replace({r'[^\x00-\x7F]+':''}, regex=True, inplace=True)
        self.df = dataframe.applymap(str)

    # I commented out the following and still receive the NameError.
    # for headerID in self.df.columns:
        # if ('UPC' or 'GTIN1' or 'GTIN' or 'EAN') in headerID:
           # header = headerID
           # self.df.rename(columns = {'%s'%header:'GTIN1'}, inplace = True)
        # if re.search(".MPN", headerID):
            # header = headerID
            # self.df.rename(columns = {'%s'%header:'MPN'}, inplace = True)
4

0 回答 0