将def函数放入Class:最多需要N个参数(给定N + 1)

时间:2016-02-22 13:23:58

标签: python python-2.7

这个功能很好用:

def create_layer(layers_list,position=0,layer_obj=None):
    if not layer_obj:
        layer_obj,created = Layer.objects.get_or_create(name=layers_list[0])   
        return create_layer(layers_list,position,layer_obj)  
    else:  
        position +=1
        if position < len(layers_list) : 
            obj,created = Layer.objects.get_or_create(name=layers_list[position],parent=layer_obj)
            return create_layer(layers_list,position,obj)
        else:
            return layer_obj

但是当我把它放到课堂上时,我得到了错误:

create_layer() takes at most 4 arguments (5 given)





class Test():

    def test1(self):
        self.create_layer(layers_list)


    def create_layer(self,layers_list,position=0,layer_obj=None):
        if not layer_obj:
            layer_obj,created = Layer.objects.get_or_create(name=layers_list[0])
            return self.create_layer(self,layers_list,position,layer_obj)
        else:
            position +=1
            if position < len(layers_list) :
                obj,created = Layer.objects.get_or_create(name=layers_list[position],parent=layer_obj)
                return self.create_layer(self,layers_list,position,obj)
            else:
                return layer_obj 

发生了什么事?

我该如何解决?

1 个答案:

答案 0 :(得分:3)

递归调用时,不要将self传递给self.create_layer。这是Python在调用类实例的方法时为您完成的。这里发生的是Python在参数列表的前面添加了另一个self,从而使它成为一个参数太多。