在Python中的类中重新分配关键字参数

时间:2018-06-28 07:01:11

标签: python

在启动类时,我坚持如何更改定义为关键字参数的属性的值。我希望能够将它们初始化为一些默认值,然后根据用户输入进行更改,但我不知道如何操作。

为说明起见,我创建了一个基于用户输入创建框的类。用户首先选择框的类型,然后选择与该框关联的属性。某些属性(例如长度,高度,宽度和颜色)是每个盒子的属性,无论类型如何。但是对于某些类型的盒子,我想询问有关其他参数的输入。我知道我可以使用以下方式打印出关键字值:

for key in kwargs:
    print("Here are my keywords and values: %s: %s" % (key, kwargs[key]))

但我不知道如何更改其值。这是我上的课。我正在寻找elif inp = '5':之后的部分,我将continue放在此处并写了我要在注释中尝试做的事情。显然,我无法调用变量extra_parameter1,那么如何访问它?

class Box():

    def __init__(self, **extra_parameters):
        self.length = 4
        self.height = 3
        self.width = 2
        self.color = None
        self.__dict__.update(extra_parameters)


    def get_parameters(self):#, *extra_parameters):
        inp = 0
        attrs = vars(self)
        while inp != '':
            for i in range(len(attrs)):
                print("{num}. {param}: {value}".format(num=i+1, param=list(attrs.keys())[i], value=list(attrs.values())[i]))
            inp = input("Enter your selection: ")
            if inp == '1':
                self.length = input("Enter the desired length: ")
            elif inp == '2':
                self.height = input("Enter the desired height: ")
            elif inp == '3':
                self.width = input("Enter the desired width: ")
            elif inp == '4':
                self.color = input("Enter the desired color: ")
            elif inp == '5':
                continue
                #self.extra_parameter1 = input("Enter the desired " + extra_parameter1 + ": ")
            elif inp == '6':
                continue
                #self.extra_parameter2 = input("Enter the desired " + extra_parameter2 + ": ")
            elif inp == '':
                print("Accept parameters")


box_type = input("Which box would you like to make?\n1. Spring\n2. Slip\n3. Prototype \n4. Two-spring\n\n")


if box_type == '1':
    spring=Box(spring_strength = 4)
    spring.get_parameters()
elif box_type == '2':
    slip=Box()
    slip.get_parameters()
elif box_type == '3':
    proto=Box()
    proto.get_parameters()
elif box_type == '4':
    two_spring=Box(left_sprint = 8, right_spring = 8)
    two_spring.get_parameters()

1 个答案:

答案 0 :(得分:2)

attrs.keys()的顺序是不确定的,因此每次您修改attrs的内容时它都可以更改。并且不能保证顺序将与您的硬编码索引相对应。

来自Python 3 docs

  

键和值以任意顺序迭代,即   非随机性,在不同的Python实现中会有所不同,具体取决于   字典的插入和删除历史记录

最好先将密钥复制到列表中,这样您就可以使用固定的(尽管仍然是任意的)顺序。然后,您可以按索引安全地访问所有参数,而无需进行硬编码:

class Box():

    def __init__(self, **extra_parameters):
        self.length = 4
        self.height = 3
        self.width = 2
        self.color = None
        self.__dict__.update(extra_parameters)

    def get_parameters(self):
        inp = 0
        attrs = vars(self)
        keys = [k for k in attrs.keys()] # store keys as a list, in order to fix their order

        while inp != '':
            for i, k in enumerate(keys):
                print("{num}. {param}: {value}".format(num=i+1, param=k.replace('_', ' '), value=attrs[k]))
            inp = input("\nEnter your selection: ")
            if inp == '':
                print("Accept parameters")
            else:
                i = int(inp) - 1
                attrs[keys[i]] = input("Enter the desired {param}: ".format(param=keys[i].replace('_', ' ')))


box_type = input("Which box would you like to make?\n1. Spring\n2. Slip\n3. Prototype \n4. Two-spring\n\n")

if box_type == '1':
    spring=Box(spring_strength = 4)
    spring.get_parameters()
elif box_type == '2':
    slip=Box()
    slip.get_parameters()
elif box_type == '3':
    proto=Box()
    proto.get_parameters()
elif box_type == '4':
    two_spring=Box(left_spring = 8, right_spring = 8)
    two_spring.get_parameters()