Python 使用format()函数调用类内的变量
这是我的代码的相同表示形式,我只想知道是否有方法从第一个操作(word)获得第二个操作(word 1)的结果。这里的主要目标是,如果我更改变量Python 使用format()函数调用类内的变量,python,Python,这是我的代码的相同表示形式,我只想知道是否有方法从第一个操作(word)获得第二个操作(word 1)的结果。这里的主要目标是,如果我更改变量字母,赋值也应该与类内的变量相对应 class Test(): def __init__(self, x='world'): self.a = 'hi {}'.format(x) self.b = 'hello' self.c = 'hey' letter = 'a' word = "Test(x
字母
,赋值也应该与类内的变量相对应
class Test():
def __init__(self, x='world'):
self.a = 'hi {}'.format(x)
self.b = 'hello'
self.c = 'hey'
letter = 'a'
word = "Test(x='{}').{}".format('new world', letter)
print(word)
# prints Test(x='new world').a, expected 'hi new world'
如果试图从对象获取属性,并且有一个包含该属性名称的字符串,则可以使用
getattr
:
class Test():
def __init__(self, x='world'):
self.a = 'hi {}'.format(x)
self.b = 'hello'
self.c = 'hey'
x = Test("new world")
letter = "a"
print(getattr(x, letter))
#output: hi new world
letter = "b"
print(getattr(x, letter))
#output: hello
如果您想“好的,但我不想多次调用
getattr
;我想只调用一次word=getattr(x,字母)
,然后每次更改letter
,它都会自动更新”。不幸的是,这在普通字符串中是不可能的,因为字符串是不可变的。创建字符串对象后,不能更改其值。您可以更改名称word
所指的内容,但每次都需要一份作业说明。非常感谢。
class Test():
def __init__(self, x='world'):
self.a = 'hi {}'.format(x)
self.b = 'hello'
self.c = 'hey'
x = Test("new world")
letter = "a"
print(getattr(x, letter))
#output: hi new world
letter = "b"
print(getattr(x, letter))
#output: hello