[英]How to use a variable as an object's name: Python
我想使用變量來訪問由 class 創建的 object 的屬性,但是 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
中的信息用作 object 名稱?
你可以這樣做:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.