轻松阅读行“参数”

时间:2020-03-03 16:11:19

标签: python

我有一个问题:

给出输入,例如:numberOfBrothers=5 anyFemale=yes 我想自动填充对象字段,例如:

def Person (self, input):
      self.brothers = input.numberOfBrothers

我做的第一件事是

john = Person(line.split(' '))

所以我有

numberOfBrothers=5 anyFemale=yes

我能以更简单的方式做到这一点,而无需在“ =”中再次分裂吗?

2 个答案:

答案 0 :(得分:0)

您需要在空格上分割,然后在=上再次分割,以获得至少键/值对的列表,我们可以将其转换为dict

>>> line = "numberOfBrothers=5 anyFemale=yes"
>>> [kv.split("=") for kv in line.split()]
[['numberOfBrothers', '5'], ['anyFemale', 'yes']]
>>> dict(_)
{'numberOfBrothers': '5', 'anyFemale': 'yes'} 

然后dict可用于为Person的调用提供关键字参数,我们将对其进行调整

class Person:
    def __init__(self, **kwargs):
        self.brothers = kwargs['numberOfBrothers']

现在我们可以使用实例化该类

john = Person(**dict([kv.split("=") for kv in line.split()]))

**语法将字典拆包,每个键/值对用作单独的关键字参数。

答案 1 :(得分:0)

您可能为此使用re.finditer

import re

class Person(object):

    def __init__(self, input):
        for match in re.finditer(r"(\w+)=(\w+)", input):
            attr_name, attr_value = match.groups()
            setattr(self, attr_name, attr_value)

john = Person("numberOfBrothers=5 anyFemale=yes")
print(john.numberOfBrothers, john.anyFemale)
相关问题