假設(shè)以下情況:class foo(object): def __init__(self, ref=None): self.ref = ref def __str__(self): return "I'm foolish"f = foo()f.ref = foo()f.ref.ref = foo()f.ref.ref.ref = foo()嘗試打?。╣etattr(f,“ ref.ref.ref”))引發(fā)'foo'對(duì)象沒有屬性'ref.ref.ref'。因此,我通過以下功能解決了該問題:def get_ref(ref_attr): for attr in ref_attr.split('.'): print(getattr(f, attr))get_ref("ref.ref.ref") retruns the expected result:I'm foolishI'm foolishI'm foolish我想知道自己,這是另一種方法還是我可以使用的內(nèi)置方法。
獲取引用對(duì)象(可變級(jí)別)的最佳方法是什么
繁星點(diǎn)點(diǎn)滴滴
2021-03-30 21:02:53