【问题标题】:How can I use the value of a variable in the name of another without using a dictionary in python?如何在不使用python中的字典的情况下以另一个名称使用变量的值?
【发布时间】:2015-11-27 03:36:39
【问题描述】:

人们已经给出的答案是:在另一个变量的赋值中使用一个变量的值:

  1. 创建字典,并且,
  2. 使用 dict[oldVariable] 而不是定义一个新变量

我认为这不适用于我正在尝试做的事情......

我正在尝试为向量定义一个类,该类将列表作为输入,并为列表的每个元素在向量中分配一个条目。

我的代码现在看起来像这样:

class vector:

    def __init__(self, entries):
        for dim in range(len(entries)):
            for entry in entries:
                self.dim = entry  #here I want to assign self.1, self.2, etc all the way to however 
                                  #many elements are in entries, but I can't replace self.dim with 
                                  # dict[dim]
    def __str__(self):
        string = []
        for entry in range(1,4):
            string.append(self.entry)
        print(string)

我该怎么做?

【问题讨论】:

  • 你甚至不能在 Python 中做self.1。为什么你坚持这样做而不是字典或简单的列表?我的意思是,self.elements[0] 可以正常工作...

标签: python class dictionary


【解决方案1】:

你在这里做的有点奇怪,因为你在 for 中使用了一个名为“dim”的变量,但是你没有对这个变量做任何事情。看起来您想像使用数组一样使用类...为什么不在类中定义数组并使用索引从外部访问它呢? v.elements[1] ...等等?

例子:

class Vector:

    def __init__(self, entries):

        self.elements = []
        for e in entries:
            self.elements.append(self.process(e))

    def __str__(self):

        buff = ''
        for e in self.elements:
            buff += str(e)
        return buff

希望这会有所帮助。

【讨论】:

  • 在我的情况下,它适用于 Python 3.4,请检查您的代码是否有任何其他问题...您能在此处发布您返回的错误吗?
  • 它在第一个 += 的 = 处给了我一个语法错误
  • 没关系,我只是在一个新程序中隔离了 += 东西,它工作正常,所以问题出在我正在使用的特定代码中,我只需要找出我做错了什么。
【解决方案2】:

如果我没有正确阅读您的问题,我认为您正在寻找 setattr 函数 (https://docs.python.org/2/library/functions.html#setattr)。

如果你想用特定的字符串值命名字段,你可以这样做:

class vector:
    def __init__(self, entries):
        for dim in range(len(entries)):
            for entry in entries:
                #self.dim = entry
                setattr(self, str(dict[dim]), dim)

这将导致您的对象self 具有以dict[dim] 的值和等于dim 的值命名的属性。

话虽如此,请注意整数值通常是一个糟糕的属性名称。您将无法在没有错误的情况下执行print obj.1。你必须这样做getattr(obj,'1')。

我同意@Ricardo 的观点,你的做法很奇怪,你可能应该重新考虑如何构建这个类,但我想直接回答这个问题,以防其他人来到这里寻找如何进行动态命名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2022-10-14
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2012-11-29
    • 2023-03-13
    相关资源
    最近更新 更多