2012-01-27 58 views
2

我想讓我的python2.x-Code兼容2.7和3.x.目前我被困在Pmw.py的一些代碼中(來自python megawidgets)。有一個看看這個字典的前三項:如何找到python3中string.atol的兼容替代方案

_standardValidators = { 
'numeric'  : (numericvalidator,  string.atol), 
'integer'  : (integervalidator,  string.atol), 
'hexadecimal' : (hexadecimalvalidator, lambda s: string.atol(s, 16)), 
'real'   : (realvalidator,   Pmw.stringtoreal), 
'alphabetic' : (alphabeticvalidator, len), 
'alphanumeric' : (alphanumericvalidator, len), 
'time'   : (timevalidator,   Pmw.timestringtoseconds), 
'date'   : (datevalidator,   Pmw.datestringtojdn), 
} 

前兩個條目包含「string.atol」。我的問題是:

  1. 在Python文檔蒂被引入作爲一個函數(string.atol(s[, base])),所以應該有括號,這是在這裏失蹤。那麼如何理解這個語法呢?

  2. 在蟒蛇3.2這段代碼引發錯誤:

    'numeric'  : (numericvalidator,  string.atol), 
    AttributeError: 'module' object has no attribute 'atol' 
    

    我已經嘗試過長替換的「蒂」三個OCCURENCES,像Python文檔建議,但只是引發的錯誤:

    'numeric'  : (numericvalidator,  string.long), 
    AttributeError: 'module' object has no attribute 'long' 
    

    因爲我甚至不理解語法,所以我對接下來要嘗試的東西感到無奈。這段代碼是如何修復的,以便它能夠在python 2.7和3.x中使用?

希望你能幫助我。

+0

「在蟒蛇3.2這段代碼引發錯誤:」 - 你忘了說的錯誤是什麼是。 – 2012-01-28 04:46:48

+0

@LennartRegebro:他確實說了什麼是錯誤信息,雖然 - 他粘貼了AttributeError。格式化有一些不足之處,但這是他的第一個。 :^) – DSM 2012-01-28 05:05:56

+0

@DSM對,你是我的壞人。格式不知何故,我的眼睛只是跳過它, – 2012-01-28 07:43:16

回答

4

1:string.atol是函數本身:函數是python中的第一類對象。括號僅用於呼叫。

>>> import string 
>>> string.atol 
<function atol at 0x00B29AB0> 
>>> string.atol("aab2", 16) 
43698L 

2:我想你一定是誤解。長時間不活在字符串中,但是Python 3中並沒有太長的時間。當Python以小方塊和長整數的方式區分用戶空間時,這是一個遺留問題。 (這是什麼「L」上43698L以上方式結束。)

簡單地使用int,即

'numeric': (numericvalidator, int), 
+0

謝謝,這工作正常。 – 2012-01-27 21:30:07

+1

很高興聽到它。傳統說,你應該點擊答案旁邊的小複選標記。 :-) – DSM 2012-01-27 21:33:13

1

當括號丟失時,您將分配函數本身,而不是函數調用的結果。請使用int替換string.atol

+0

'長'不存在於Python 3.2,但。 – DSM 2012-01-27 21:16:03

+0

@DSM,謝謝 - 我認爲如此,但不確定。我仍然在2.7。 – 2012-01-27 21:22:47