我遇到了這個問題,當我實體化一個 Test 物件并呼叫 main() 方法時,它會列印出來
https://bunch/of/urls/with/None/
雖然我期待有
https://bunch/of/urls/with/1234/
它不能self.id稍后在主函式內更新字典 f 字串的內部。
我的期望是當字典值檢索給定鍵時,它會self.id在回傳值的同時更新。
我期待的原因是因為我在打電話self.b_func(1234)之前打電話self.a_func()所以它會更新self.id.
但是,它不會更新self.idf 字串的內部。這種行為我不明白為什么。我錯過了什么概念?我怎樣才能解決這個問題?
class Test():
def __init__(self,id=None):
self.id = id
# Problem happens here
self.a_dict = {'a' : f'https://bunch/of/urls/with/{self.id}/'}
def a_func(self):
val = self.a_dict['a']
print(val)
# It prints
# https://bunch/of/urls/with/None/
# Not
# https://bunch/of/urls/with/1234/
def b_func(self, id):
self.id = id
return True
def main(self):
self.b_func(1234)
self.a_func()
if __name__ == '__main__':
a = Test()
a.main()
uj5u.com熱心網友回復:
f 字串在它們定義的地方進行評估。當內部運算式的值隨后發生變化時,它們不會神奇地更新自己。
您可以考慮創建a_dict一個屬性,以便動態生成其值:
class Test():
def __init__(self,id=None):
self.id = id
@property
def a_dict(self):
return {'a' : f'https://bunch/of/urls/with/{self.id}/'}
演示:https ://replit.com/@blhsing/UnnaturalElasticClasslibrary
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524393.html
下一篇:為什么我的正則運算式回傳無?
