class first:
class second:
class third:
class forth:
val = "test"
我想安全地取回變量「VAL」。在「VAL」不存在我想返回False(而不是顯示錯誤)驗證屬性在嵌套類
我知道我可以使用邏輯運算符是這樣的:
打印first.second和first.second.third和first.second.third.forth和first.second.third.forth.val或假
或把它放在一個'嘗試...除了'像這樣的塊:
try :
print first.second.third.forth.val
except AttributeError:
pass
但上述兩個例子實在太長了,當他們有太多的嵌套類
我的問題是,有沒有其他更簡單的方法來做到這一點尤其要閱讀?我希望有像這樣的東西。在C#中的運算符或至少可以安全評估並易於閱讀的函數。
我的問題是類似這樣的問題:How to know if an object has an attribute in Python
但不同的是,我的是在嵌套類,如果我使用hasattr()或GETATTR()我仍然有錯誤,當一個類是缺少這樣的:
>>> class first:
... class second:
... class third:
... class forth:
... val = "test"
...
>>> hasattr(first.second.third.forth.fifth,'val')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class forth has no attribute 'fifth'
但它確實給我一個想法,創建這樣一個功能:
>>> def eval(cls, args, default=False):
... for arg in args.split('.') :
... if not hasattr(cls,arg) : return default
... cls = getattr(cls,arg)
... return cls
...
>>> eval(first,'second.third.forth.val','Default Value')
'test'
>>> eval(first,'second.third.forth.fifth','Default Value')
'Default Value'
這樣的幾個級別的嵌套類會讓你的代碼更難以閱讀。如果可能,儘量平整它。 – TigerhawkT3
x?.y - null條件成員訪問。如果左操作數爲null,則返回null。 這不說存在。 – saikumarm
@ TigerhawkT3謝謝,我會盡可能地將它弄平。 – SDBot