繁体   English   中英

如何在Python中使用逗号分隔变量的列表字符串来函数参数?

[英]How do I use a list string of comma separated variables to function arguments in Python?

我有一个字符串列表,其中包含类构造函数的参数。 我需要将字符串列表转换为CallDetail对象的列表。 该列表必须在名为Util的类中创建

class CallDetail:
    def __init__(self, phoneno, called_no, duration, call_type):
        self.__phoneno=phoneno
        self.__called_no=called_no
        self.__duration=duration
        self.__call_type=call_type

call='9990000001,9330000001,23,STD'
call2='9990000001,9330000002,54,Local'
call3='9990000001,9330000003,6,ISD'

list_of_call_string=[call,call2,call3]

我已经试过了----

class Util:
    def __init__(self):
        self.list_of_call_objects=None

    def parse_customer(self,list_of_call_string):
        for i in range(0,3):
            info=list_of_call_string[i].split(",")
            ob=CallDetail(info[0],info[1],info[2],info[3])
            self.list_of_call_objects.append(ob)
        pass

这是行不通的,因为我们无法附加'NoneType'

改变self.list_of_call_objectslist类型不继续保持none

class Util:
    def __init__(self):
        self.list_of_call_objects=[]

这将解决您的问题。

当通过注释OP不想在Util类中更改类型时,他可以在函数调用中更改其类型。

class Util:
    def __init__(self):
        self.list_of_call_objects=None

    def parse_customer(self,list_of_call_string):
        self.list_of_call_objects = list()
        for i in range(0,3):
            info=list_of_call_string[i].split(",")
            ob=CallDetail(info[0],info[1],info[2],info[3])
            self.list_of_call_objects.append(ob)
        pass

这是另一种解决方案。

def parse_customer(self, list_of_call_string):
   self.list_of_call_objects = [CallDetail(*info.split(',')) for info in list_of_call_string]

暂无
暂无

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

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