[Python] super() 只能用在 new style class 上

[Python] super() 只能用在 new style class 上

昨天改完 python 的程式,很高興地就送去 build 了,

隔天才發現有 pylint 的錯誤,

而且這個問題在 python 2.6 才出現,python 2.7 是沒有問題的…

************* Module test
E:  5, 4: Use of super on an old style class (super-on-old-class)

 

看了一下寫的程式,原來是因為我寫了一個繼承自 logging.handlers.RotatingFileHandler 的 class,

然後我在 class 裡面寫了一個函式呼叫到 super(MyRotatingFileHandler, self).__init__() ~

from logging.handlers import RotatingFileHandler
class MyRotatingFileHandler(RotatingFileHandler):
def __init__(self, filename):
super(MyRotatingFileHandler, self).__init__(filename)
print "init my handler"
x = MyRotatingFileHandler("test.log")

 

直接在 python 2.6 上執行的話,會有類似下面的錯誤:

Traceback (most recent call last):
File "test.py", line 8, in <module>
x = MyRotatingFileHandler("test.log")
File "test.py", line 5, in __init__
super(MyRotatingFileHandler, self).__init__(filename)
TypeError: super() argument 1 must be type, not classobj

 

如果去查 python 的原始碼,就可以看到他們的 base class 是不一樣的:

  – python 2.6: RotatingFileHandler -> BaseRotatingHandler -> FileHandler -> StreamHandler -> Handler -> Filterer

  – python 2.7: RotatingFileHandler -> BaseRotatingHandler -> FileHandler -> StreamHandler -> Handler -> Filterer -> object

 

就只差在 python 2.7 的 class 是有從 object 繼承下來的 (所謂的 new style class),

因此才可以呼叫 super(),如果不是 new style class 的話就不能呼叫 super() 了~

(可參考 python Built-in Functions: super() 的說明)

 

只能改成直接呼叫 RotatingFileHandler.__init__(),而不能透過 super() 來呼叫。

程式改完之後如下:

from logging.handlers import RotatingFileHandler
class MyRotatingFileHandler(RotatingFileHandler):
def __init__(self, filename):
RotatingFileHandler.__init__(self, filename)
print "init my handler"
x = MyRotatingFileHandler("test.log")

 

 

(本頁面已被瀏覽過 454 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料