
[英]python trying to pass list in as variable in function TypeError: 'int' object is not iterable
[英]Trying to pass list of variable in class and function in object oriented manner
我试图以面向对象的方式在类和函数中传递变量列表,但是遇到一些错误,我不明白它有什么问题,我正在Eclipse中使用PyDev
class Mydetails:
__details = ''
def __init__(self,details): # constructor
#self.__details['country'] = details['country']
self.__details = details
def set_element(self,details):
self.__details = details
def get_list(self,details):
return self.__details
details = ['ABC','DEF','GHI','JKL']
pdetails = Mydetails()
pdetails.set_element(details)
print(pdetails.get_list())
Traceback (most recent call last):
File "C:\workspace\python\pythonapp\list.py", line 18, in <module>
pdetails = Mydetails()
TypeError: __init__() missing 1 required positional argument: 'details'
在这一行:
def __init__(self,details):
您使init函数采用了一个参数( details ),但是在这里:
pdetails = Mydetails()
您不给它一个参数! 您可能想在那里做的是:
pdetails = Mydetails(details)
附带一提,您的def get_list(self,details):
函数没有意义,为什么要向其传递一个不会被使用的参数?
我修复了我的代码,这是函数def get_list(self,details):
更改为def get_details(self):
因为details参数已经复制到self中,所以不允许使用相同的代码来抛出错误,但是下面的代码已修复并与函数调用和定义的对象也可以正常工作,与之前的代码相同。
class Mydetails:
__details = '' #protected
def __init__(self,details={}): # constructor
self.__details = details
def set_details(self,details): # function
self.__details = details
def get_details(self):
return self.__details
def toString(self):
return 'Welcome {}'.format(self.__details)
new_details = ['xyz','klm','nop']
pdetails = Mydetails()
pdetails.set_details(new_details)
print(pdetails.get_details())
['xyz', 'klm', 'nop']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.