简体   繁体   English

尝试以面向对象的方式传递类和函数中的变量列表

[英]Trying to pass list of variable in class and function in object oriented manner

I'm trying to pass variable list in Class and Function in object oriented manner but facing some error, I don't understand what wrong with it and I'm using PyDev in Eclipse 我试图以面向对象的方式在类和函数中传递变量列表,但是遇到一些错误,我不明白它有什么问题,我正在Eclipse中使用PyDev

CODE

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())

OUTPUT 输出值

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'

in this line: 在这一行:

def __init__(self,details):  

you made the init function take a parameter ( details ), but here: 您使init函数采用了一个参数( details ),但是在这里:

pdetails = Mydetails()  

you arent giving it a parameter! 您不给它一个参数! what you probably wanted to do there is: 您可能想在那里做的是:

pdetails = Mydetails(details)

on a side note your def get_list(self,details): function doesn't make sense, why are you passing it a parameter that doesn't get used? 附带一提,您的def get_list(self,details):函数没有意义,为什么要向其传递一个不会被使用的参数?

I fixed my code ,It was error in function def get_list(self,details): changed to def get_details(self): because details parameter already copied in self so it not allow the same thats why throwing error, but below code is fixed and work fine with function calling and defined object also correct from previous code. 我修复了我的代码,这是函数def get_list(self,details):更改为def get_details(self):因为details参数已经复制到self中,所以不允许使用相同的代码来抛出错误,但是下面的代码已修复并与函数调用和定义的对象也可以正常工作,与之前的代码相同。

CODE

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())

OUTPUT 输出值

['xyz', 'klm', 'nop']

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

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