我是python的新手。我在下面的代码中得到“主实例没有调用方法”错误。我正在尝试在主类中创建产品类对象并调用产品使用这些对象的类函数。这样做的正确方法是什么,以免出现这样的错误。
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])
答案 0 :(得分:1)
写作时
product = main()
使用product
的实例替换绑定到main
的类。稍后,当您尝试创建product
的实例时,实际上是在尝试将main
的实例作为函数调用。
您需要使用不同的名称,最简单的方法是遵循用户定义的类名以大写字母开头的约定,所有其他名称(不包括CONSTANTS
)以小写名称开头
import sys
from sys import argv
class Read():
...
class Product():
...
class Main():
...
# This is a bad name, by the way. If you have two classes named Product
# and Main, a variable named product seems far more likely to be an
# instance of Product, not Main.
product = Main()
product.main_function()
答案 1 :(得分:0)
他们回答你的评论
class product():
与
冲突product=main()
因此产品不再是类名。请将您的课程的首字母大写或更好地看看PEP8