Python: __init__() takes 2 arguments (3 given)

2024-05-21 11:49:43 发布

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

我正在编写一个程序来查找适配器,并创建了一个名为“Adapter”的类。当我传入两个参数时,IDLE给了我一个错误,说我传入了三个!下面是代码和堆栈跟踪:

#This is the adapter class for the adapter finder script

class Adapter:
    side1 = (None,None)
    side2 = (None,None)
    '''The class that holds both sides of the adapter'''
    def __init__((pType1,pMF1),(pType2,pMF2)):
        '''Initiate the adapter.

        Keyword Arguments:
        pType1 -- The passed type of one side of the adapter. ex: BNC, RCA
        pMF1 -- The passed gender of pType1. ex: m, f

        pType2 -- The passed type of one side of the adapter. ex: BNC, RCA
        pMF2 -- The passed gender of pType2. ex: m, f

        '''

        print 'assigining now'
        side1 = (pType1,pMF1)
        print side1
        side2 = (pType2,pMF2)
        print side2

sideX = ('rca','m')
sideY = ('bnc','f')

x = Adapter(sideX,sideY)
print x.side1
print x.side2

错误: Traceback (most recent call last): File "C:\Users\Cody\Documents\Code\Python\Adapter Finder\adapter.py", line 28, in <module> x = Adapter(sideX,sideY) TypeError: __init__() takes exactly 2 arguments (3 given)

我不明白问题是什么,因为我只输入了两个参数!

编辑:我是python语言的新手,虽然我懂Java。 我将此页用作教程:http://docs.python.org/tutorial/classes.html


Tags: ofthenoneadapterclassexprintpassed
4条回答

您的__init__应该如下所示:

def __init__(self,(pType1,pMF1),(pType2,pMF2)):

方法调用会自动获取“self”参数作为第一个参数,因此使__init__()看起来像:

def __init__(self, (pType1,pMF1),(pType2,pMF2)):

这通常在其他语言中是隐式的,在Python中必须是显式的。还要注意,这实际上只是通知它所属实例的方法的一种方式,您不必将其称为“self”。

是的,OP漏掉了self,但我甚至不知道那些元组作为参数意味着什么,我故意不去想办法弄清楚,这只是一个糟糕的构造。

Codysehi,请将您的代码与:

class Adapter:
    def __init__(self, side1, side2):
        self.side1 = side1
        self.side2 = side2

sideX = ('rca', 'm')
sideY = ('bnc', 'f')
x = Adapter(sideX, sideY)

你要明白,这本书可读性更高,而且也符合我的想法。

相关问题 更多 >