我正在编写一个程序来查找适配器,并创建了一个名为"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
Run Code Online (Sandbox Code Playgroud)
错误:
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
msw*_*msw 20
是的,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)
Run Code Online (Sandbox Code Playgroud)
并且看到它更具可读性,并且做我认为你想要的.
小智 13
方法调用自动获取'self'参数作为第一个参数,因此make __init__()看起来像:
def __init__(self, (pType1,pMF1),(pType2,pMF2)):
Run Code Online (Sandbox Code Playgroud)
这通常隐含在其他语言中,在Python中它必须是显式的.另请注意,它实际上只是一种通知它所属实例的方法的方法,您不必将其称为"自我".
你__init__应该看起来像这样:
def __init__(self,(pType1,pMF1),(pType2,pMF2)):
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58954 次 |
| 最近记录: |