将文件记录插入对象然后插入字典

时间:2016-11-01 12:09:58

标签: python dictionary

class Customer:
    def __init__(self,custid,name,addr,city,state,zipcode):
        self.custid=custid
        self.name=name
        self.addr=addr
        self.city=city
        self.state=state
        self.zipcode=zipcode
        self.memberLevel=BasicMember()
        self.monthlySpending =0

    def changeLevel(self,level):
        if level == 'gold':
            self.memberLevel = GoldMember()        
        elif level == 'silver':
            self.memberLevel = SilverMember()
        else:
            self.memberLevel = BasicMember()

以上是我的客户类。我试图从文件中读取客户数据并将其映射到客户类对象。之后我想在字典中插入每个对象。目前我遇到了麻烦,因为它给了我一个错误:

cc=Customer.Customer(*item)
TypeError: __init__() takes 7 positional arguments but 61 were given.

Customer1是我导入的模块的名称。

for line in open('customers.dat','r'):
    item=line.rstrip()
    cc=Customer1.Customer(*item)
    s2=item.split(',',1)[0]
    d[s2]=[cc]

以下是我的Customer.dat文件中的一些示例数据:

310933237,Temmin Wexley,898 Sullustan Street,Geonosis,MA,02100
286659823,Mace Windu,741 Bantha Street,Jakku,MA,02330
234101312,Wuher,932 Besalisk Street,Coruscant,MA,02169
721728168,Yaddle,30 Amani Road,D'Qar,MA,01508
492621787,Yoda,860 Amani Road,Endor,NH,03801

1 个答案:

答案 0 :(得分:0)

当你拨打Customer(*item)时,你正在传递一个字符串(例如“310933237,Temmin Wexley,898 Sullustan Street,Geonosis,MA,02100”),因此它会扩展到参数列表3,1,0 ,9,......等。

将其更改为:

item=line.rstrip()
input = line.split(',')
cc = Customer(*input)

让你的论点正确分开。