繁体   English   中英

Python:__ init __()只需2个参数(给定3个)

[英]Python: __init__() takes exactly 2 arguments (3 given)

我正在编写一个程序来查找适配器,并创建了一个名为“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)

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

编辑:虽然我认识Java,但我是python语言的新手。 我正在使用此页面作为教程: http//docs.python.org/tutorial/classes.html

是的,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)

并且看到它更具可读性,并且做我认为你想要的。

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

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

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

你的__init__应该是这样的:

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

看起来这就是Python向每个人学习语言问好的方式。 Python的第一口。

您必须在实例方法中指定self作为第一个参数。 所以它应该是。

  def __init__( self, (pType1,pMF1),(pType2,pMF2)):
class Adapter:
side1 = (None,None)
side2 = (None,None)
'''The class that holds both sides of the adapter'''
def __init__(self,(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'
    self.side1 = (pType1,pMF1)#i have changed from side1 to self.side1
    print self.side1#i have changed from side1 to self.side1
    self.side2 = (pType2,pMF2)#i have changed from side1 to self.side2
    print self.side2#i have changed from side1 to self.side2
sideX = ('rca','m')
sideY = ('bnc','f')

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

看下面的输出。

程序输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM