在类

时间:2017-05-17 00:50:58

标签: python python-2.7 python-3.x

我有一个简单的Python程序,有2个类。我正在尝试将A类中的变量打印到B类中。

代码:

import sys
import csv


#This class reads in the command line args and assigns them to variables
class main:
    def __init__(self):
        #print program name
        print ("PRIT0 Analyser Tool Running...")
        #print the usage
        print ("[csv file] [errorfile] [prit0 time] ")
        #handle the arguments
        if (len(sys.argv) < 4):
            print("You are missing parameters!")
        else:
            #create variables to hold args
            csv_file   = ""
            err_file   = ""
            prt_0      = 0.0
            #assign command line args to variables
            csv_file = sys.argv[1]
            err_file = sys.argv[2]
            prt_0    = sys.argv[3]
            ob_c.readCsvFile()


#This class will read in the csv file and handle the data analysis
class csv:
    def readCsvFile():
        print(ob_m.csv_file)


#class instances
ob_m = main
ob_c = csv 

if __name__ == '__main__':
    main()

错误:

'Type object 'main' has no attribute to 'csv_file'

不确定我为什么会遇到这个问题。任何想法将不胜感激

2 个答案:

答案 0 :(得分:1)

这看起来很像Java的翻译,它可能与非Pythonic有关。

  1. 拥有交叉链接的全局变量通常不是一个好习惯(比如引用全局ob_m的csv类和引用全局ob_c的主类)
  2. 仅为副作用实例化对象(如在主要__init__中触发ob_c.readCvsFile())也不是一个很好的做法
  3. __init__函数应填充对象或引发异常(在您的情况下,如果参数数量太少,则返回不可用的实例)
  4. 由于__init__在将对象分配给变量ob_m之前发生,因此在调用readCsvFile时仍然未定义,因此没有办法让它以这种方式工作
  5. 将您的类命名为与导入的名称相同(名称阴影)
  6. 是一个坏主意

    也就是说,您的代码可以重写为如下工作

    import sys
    import csv
    
    #This class reads in the command line args and assigns them to variables
    class main:
        @staticmethod
        def build_main():
            #print program name
            print ("PRIT0 Analyser Tool Running...")
            #print the usage
            print ("[csv file] [errorfile] [prit0 time] ")
            #handle the arguments
            if (len(sys.argv) < 4):
                print("You are missing parameters!")
                return None
            else:
                return main(sys.argv[1], sys.argv[2], sys.argv[3])
    
        def __init__(self, csv_file, err_file, prt_0):
            self.csv_file = csv_file
            self.err_file = err_file
            self.prt_0 = prt_0
    
        def run(self):
            ob_c.readCsvFile()
    
    
    #This class will read in the csv file and handle the data analysis
    class my_csv:
        def readCsvFile():
            print(ob_m.csv_file)
    
    
    #class instances
    ob_c = my_csv 
    
    if __name__ == '__main__':
        ob_m = main.build_main()
        if ob_m is not None:
            ob_m.run()
    

    此解决方案仍然存在全局变量的问题。从标准的Python实践中,最好在main中创建my_csv实例作为成员

        def __init__(self, csv_file, err_file, prt_0):
            self.csv_file = csv_file
            self.err_file = err_file
            self.prt_0 = prt_0
            self.my_csv = my_csv
    
        def run(self):
            self.my_csv.readCsvFile()
    

    或作为运行中的临时对象

        def run(self):
            ob_c = my_csv
            ob_c.readCsvFile()
    

    最后,还有对全局主对象的引用,它也是非显式的。最好将它作为参数传递给readCsvFile

    class main:
    
        ...
    
        def run(self):
            ob_c = my_csv
            ob_c.readCsvFile(self)
    
    
    #This class will read in the csv file and handle the data analysis
    class my_csv:
        def readCsvFile(ob_main):
            print(ob_main.csv_file)
    

    最终代码如下:

    import sys
    import csv
    
    #This class reads in the command line args and assigns them to variables
        class main:
            @staticmethod
            def build_main():
                #print program name
                print ("PRIT0 Analyser Tool Running...")
                #print the usage
                print ("[csv file] [errorfile] [prit0 time] ")
                #handle the arguments
                if (len(sys.argv) < 4):
                    print("You are missing parameters!")
                    return None
                else:
                    return main(sys.argv[1], sys.argv[2], sys.argv[3])
    
            def __init__(self, csv_file, err_file, prt_0):
                self.csv_file = csv_file
                self.err_file = err_file
                self.prt_0 = prt_0
    
            def run(self):
                ob_c = my_csv
                ob_c.readCsvFile(self)
    
    
        #This class will read in the csv file and handle the data analysis
        class my_csv:
            def readCsvFile(ob_main):
                print(ob_main.csv_file)
    
    
    if __name__ == '__main__':
        ob_m = main.build_main()
        if ob_m is not None:
            ob_m.run()
    

    我希望它有所帮助

答案 1 :(得分:0)

为了实例化一个类,你需要在它之后加上括号:

ob_m = main()

同样,当你在最后一行中说main()时,它只是实例化那个类。你应该把它变成一个函数。