2014-09-05 57 views
0

我有一個protobuf消息,並且消息有一個變量,名稱是「pass」,它是python中的一個關鍵字。我可以把關鍵字作爲一個公共變量?

我得到一個錯誤,如:

「語法錯誤:無效的語法」

而我分配一個號碼,以「通」的說法:

msg.pass = 1 

我應該怎麼做,如果我不不想重命名「傳遞」到「xxpass」?謝謝。

+0

爲了什麼它的價值,通常的慣例,當你想在一個鍵後命名一個變量單詞是附加下劃線:'pass_','type_'等 – dano 2014-09-05 02:32:05

回答

4

您可以使用setattr它說:

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

你的情況

所以,你可以使用:

setattr(msg, 'pass', 1) 

注意,找回它,你會需要它的getattr對應:

val = getattr(msg, 'pass') 
+5

雖然你必須記住,規則通常是有原因的。避免在保留字之後命名標識符是一個很好的練習。 – MattDMo 2014-09-05 02:24:16

+0

謝謝,它解決了我的問題! – Mark 2014-09-05 02:27:39

相關問題