Python构造函数副本

2024-09-27 00:20:29 发布

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

我试图测试我的程序以创建对象的副本,但出现以下错误:

TypeError: __init__() takes 1 positional argument but 2 were given

我试图检查现有问题,但无法更正此错误。有什么建议吗?你知道吗

这是我的课:

class ordred_dict:
    #"""
    #This class is an ordred dictionary
    #composed of 2 listes: key list and value list as a dictionary
    #"""
    def __init__(self, orig):
    #"""
    #Constructur to initiate an empty key and value list 
    #"""
        self.key_list=list(orig.key_list)
        self.value_list=list(orig.value_list)
    def __init__(self, **Tuplekeysvalues):
        #"""
        #Create a new dict using a liste of (keys:values)
        #"""
        self.key_list=list()
        self.value_list=list()
        for key in Tuplekeysvalues:
            self.key_list.append(key)
            self.value_list.append(Tuplekeysvalues[key])
            #print("({}:{}) ".format(key, Tuplekeysvalues[key]))

#Main program
dict3=ordred_dict(p1="1",p2="2",p4="4",p3="3",p0="0")
dict2=ordred_dict(dict3)

Tags: andofkeyselfandictionaryinitvalue
1条回答
网友
1楼 · 发布于 2024-09-27 00:20:29

在Python中不能像在其他语言中那样重载构造函数。更好的方法是:

class MyOrderedDict:
    def __init__(self, *args):
        self.key_list = []
        self.value_list = []
        for key,val in args:
            self.key_list.append(key)
            self.value_list.append(val)

    @classmethod
    def from_ordered_dict(cls, other):
        return cls(*zip(other.key_list, other.value_list))

那就叫它:

d = MyOrderedDict(('key1', 'value1'), ('key2', 'value2'))
e = MyOrderedDict.from_ordered_dict(d)

相关问题 更多 >

    热门问题