Python 使用字符串作为指针调用元组值
''如何使用字符串'Letter'调用元组'a'?''您需要内置的Python 使用字符串作为指针调用元组值,python,string,variables,tuples,Python,String,Variables,Tuples,''如何使用字符串'Letter'调用元组'a'?''您需要内置的getattr函数: import string count = 0 # Button press Counter Letter = string.ascii_lowercase[count] print(Letter) # returns string, a class Colours: a = (255,0,0) #Tuple to be called print(Colours.Letter[0:3]) #retu
getattr
函数:
import string
count = 0 # Button press Counter
Letter = string.ascii_lowercase[count]
print(Letter) # returns string, a
class Colours:
a = (255,0,0) #Tuple to be called
print(Colours.Letter[0:3]) #returns Attribute Error: class Colours has no attribute 'Letter'
您可以使用访问属性的名称(作为字符串) 从:
getattr(对象,名称[,默认])
返回对象的命名属性的值。名称必须是字符串。如果字符串是对象属性之一的名称,则结果是该属性的值。例如,getattr(x,'foobar')等同于x.foobar。如果命名属性不存在,则返回默认值(如果提供),否则将引发AttributeError
只需使用getattr()
函数,它就是为此而设计的
getattr(Colours, Letter)
请澄清你的问题。不能调用元组;你调用一个函数。如果您试图访问元组,
Letter
如何与该访问相关?你的程序逻辑一点也不明显。
getattr(Colours, Letter)
class Colours:
a = (255,0,0) #Tuple to be called
print(getattr(Colours, 'a'))