Python:为什么超级类的方法没有看到?

时间:2013-06-12 20:04:19

标签: python class logging twisted

我正在尝试实现我自己的DailyLogFile

版本
from twisted.python.logfile import DailyLogFile

class NDailyLogFile(DailyLogFile):

     def __init__(self, name, directory, rotateAfterN = 1, defaultMode=None):
         DailyLogFile.__init__(self, name, directory, defaultMode)   # why do not use super. here? lisibility maybe?
         #
         self.rotateAfterN = rotateAfterN

    def shouldRotate(self):
         """Rotate when N days have passed since file creation"""
         delta = datetime.date(*self.toDate()) - datetime.date(*self.toDate(self.createdOn)) 
         return delta > datetime.timedelta(self.rotateAfterN)

    def __getstate__(self):
        state = BaseLogFile.__getstate__(self)
        del state["rotateAfterN"]
        return state

threadable.synchronize(NDailyLogFile)

但看起来我错过了Python子类化过程的基础...因为我得到了这个错误:

Traceback (most recent call last):
  File "/home/twistedtestproxy04.py", line 88, in <module>
    import ndailylogfile
  File "/home/ndailylogfile.py", line 56, in <module>
    threadable.synchronize(NDailyLogFile)
  File "/home/lt/mpv0/lib/python2.6/site-packages/twisted/python/threadable.py", line 71, in synchronize
    sync = _sync(klass, klass.__dict__[methodName])
KeyError: 'write'

所以我需要明确添加和定义其他方法,如Writerotate方法,如下所示:

class NDailyLogFile(DailyLogFile):
     [...]
     def write(self, data): # why must i add these ?
         DailyLogFile.write(self, data)

     def rotate(self): # as we do nothing more than calling the method from the base class!
            DailyLogFile.rotate(self)

threadable.synchronize(NDailyLogFile)

虽然我认为它将从基础母班正确继承。请注意,我什么都不做,只叫“超级”,

请问有人可以解释为什么我错误地认为没有必要添加Write方法吗?

有没有办法在我的NDailyLogFile中对Python说,它应该有没有直接从其母类定义的所有方法DailyLogFile?这样就可以防止这个错误之王_sync(klass, klass.__dict__[methodName]并避免明确地指定错误?

(DailyLogFile的原始代码激励我从这里扭曲的来源获取https://github.com/tzuryby/freespeech/blob/master/twisted/python/logfile.py

编辑:关于使用super,我得到:

  File "/home/lt/inwork/ndailylogfile.py", line 57, in write
    super.write(self, data)
exceptions.AttributeError: type object 'super' has no attribute 'write'

所以不会使用它。我觉得它是对的...我必须明确地错过了一些东西

2 个答案:

答案 0 :(得分:3)

有一种解决方法,只需:

NDailyLogFile.__dict__ = dict( NDailyLogFile.__dict__.items() + DailyLogFile.__dict__.items() )
threadable.synchronize(NDailyLogFile)

这里存在一个问题,即您在没有实例化的情况下使用该类。此解决方法有效,因为您在实例化之前强制更改类属性。

另一个重要的评论是,对于DailyLogFile的子类,命令super不起作用,因为DailyLogFile是所谓的“旧样式类”或“classobj”。 super仅适用于“新样式”类。 See this question for further information about this

答案 1 :(得分:2)

我敢说twisted/python/threadable.py代码中有一个错误。 __dict__仅返回本地属性,而不返回继承的属性。 Other posts说要使用dir()inspect.getmembers()来获取它们。

好消息是,您认为write方法是继承的第一个想法是正确的。坏消息是Twisted不承认继承的方法,所以你必须自己编写它们。