AttributeError:主实例没有调用方法

2024-03-28 10:03:42 发布

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

我是python新手,在下面的代码中遇到“main instance has nocallmethod”错误,我试图在main类中创建产品类对象,并使用这些对象调用产品类函数。正确的方法是什么来避免这种错误。在

import sys
from sys import argv

class read():

    def __init__(self):
        return

    def read_function(self):
        self.file_one=open(argv[1],"r")
        self.file_two=open(argv[2],"w")
        return self.file_one,self.file_two

class product():

    def calculate(self,calc_row):
        self.calc_row=calc_row
        if "India" in calc_row[3]:
            print "In India"            
            self.tax_amt=int(calc_row[2])*5/100
            self.final_amt=self.tax_amt+int(calc_row[2])

        elif "US" in calc_row[3]:
            print "In US"            
            self.tax_amt=int(calc_row[2])*10/100
            self.final_amt=self.tax_amt+int(calc_row[2])
        else:
            print "In UK"            
            self.tax_amt=int(calc_row[2])*15/100 
            self.final_amt=self.tax_amt+int(calc_row[2])


        return self.tax_amt,self.final_amt


    def writerow(self,out_file,list,tax_am,final_am):
        self.list=data
        self.tax_am=tax_val
        self.final_am=final_val
        self.out_file=out_data
        self.string=",".join(self.list)
        self.string=self.string+","+str(self.tax_am)+","+str(self.final_am)+"\n"
        print self.string
        self.out_file.write(self.string)        

class main():
    def __init__(self):
        return

    def main_function(self):
        read_obj=read()

        self.in_data,self.out_data=read_obj.read_function()    
        self.prod_list = [product() for i in range(3)]

        for self.index,self.line in enumerate(self.in_data):
            if (self.index == 0):
                self.header=self.line
                self.header=self.header.replace("\n","")
                self.header=self.header+",Sales_Tax,Final_Price \n"
                self.out_data.write(self.header)
            else: 
                self.line.replace("/n","")
                self.data=self.line.split(",")
                self.prod=self.prod_list[index-1]
                self.tax_val,self.final_val=self.prod.calculate(self.data)
                print "Tax %d Final %d"% (self.tax_val,self.final_val)
                self.prod.writerow(self.out_data,self.data,self.tax_val,self.final_val)


product=main()
product.main_function()
write_obj=write()
print type(prod_list[0])

Tags: inselfreaddatamaindefcalcval
2条回答

当他们回答你的评论时

class product():

与…冲突

^{pr2}$

所以产品不再是类名了。请把你们班的第一个字母大写,或者最好看一下PEP8

当你写作的时候

product = main()

将绑定到product替换为main的实例。稍后,当您尝试创建product的实例时,实际上是在尝试将main的实例作为函数调用。在

您需要使用不同的名称,最简单的方法是遵循以下约定:用户定义的类名以大写字母开头,所有其他名称(不包括CONSTANTS)以小写字母开头。在

^{pr2}$

相关问题 更多 >