python构造函数中的参数不匹配

时间:2018-06-04 05:03:47

标签: python python-3.x

我编写了一个python类,其构造函数将两个列表作为参数。

class nn:
    def __init__(layer_dimensions=[],activations=[]):

        self.parameters = {} 
        self.cache = []      
        self.activations= []

        initialize_parameters(layer_dimensions)
        initialize_activations(activations)

net = nn(list([2,15,2]),list(['relu','sigmoid']))

在尝试在构造函数中传递两个列表作为参数时,我收到以下错误:

TypeError: __init__() takes from 0 to 2 positional arguments but 3 were given

错误表明已经传递了3个参数,但很明显我只传了2个。

3 个答案:

答案 0 :(得分:1)

你错过了自我作为调用类方法的实例自动传递。

class nn:
    def __init__(self, layer_dimensions=[],activations=[]):

        self.parameters = {} 
        self.cache = []      
        self.activations= []

        initialize_parameters(layer_dimensions)
        initialize_activations(activations)

net = nn(list([2,15,2]),list(['relu','sigmoid']))

答案 1 :(得分:1)

我相信你在构造函数中缺少一个自我

class nn:
    def __init__(self, layer_dimensions=[],activations=[]):

        self.parameters = {} 
        self.cache = []      
        self.activations= []

        initialize_parameters(layer_dimensions)
        initialize_activations(activations)

net = nn(list([2,15,2]),list(['relu','sigmoid']))

答案 2 :(得分:1)

此外,默认参数是可变的并不是一个好习惯。您可以阅读更多相关信息here