【问题标题】:How to use a variable as an object's name: Python如何使用变量作为对象的名称:Python
【发布时间】:2022-01-03 18:14:43
【问题描述】:

我想使用变量来访问由类创建的对象的属性,但是 Python 使用变量的名称作为对象的名称,而不是存储在变量中的名称。

class button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

white = (255,255,255).

A1 = button(white, 50, 50, 20, 20, text='Hello World')


var = "A1"

print(var.text)

当我运行它时:


AttributeError: 'str' object has no attribute 'text'

有没有办法在调用var.text时使用var里面的信息作为对象名?

【问题讨论】:

  • 这能回答你的问题吗? How do I create variable variables?
  • 变量名是为了编码者的利益,而不是代码本身。如果你的代码需要一个变量名,这意味着你应该使用dict
  • 应该避免 - 但print(eval(var).text) 也可以。
  • 任何时候你想Variable variablesdict(或其他语言,关联数组)。任何其他通过变通方法或可怕的php 之类的废话来实现这一点的方法都会造成混乱,并且可能会在下一个开发人员看到您的代码时导致您的生活。

标签: python class attributeerror


【解决方案1】:

你可以这样做:

class button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

white = (255,255,255)

A1 = button(white, 50, 50, 20, 20, text='Hello World')


var = "A1"

print(locals()[var].text)

【讨论】:

  • 但是使用字典肯定更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 1970-01-01
  • 2015-11-28
  • 2013-12-03
相关资源
最近更新 更多