简体   繁体   English

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

[英]Python : why a method from super class not seen?

i am trying to implement my own version of a DailyLogFile 我正在尝试实现我自己的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)

but it looks like i miss a fundamental of Python subclassing process...as i get this error : 但它看起来我错过了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'

so i need to explicitly add and define others methods like Write and rotate method like this: 所以我需要显式添加和定义其他方法,如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)

while i thought it would be correctly inherit from the base mother class. 虽然我认为它将正确地从基础母班继承。 Notice that i do nothing, only calling "super", 请注意,我什么都不做,只叫“超级”,

please can someone explain why i am wrong on my first idea that it was not necessary to add the Write method? 请有人解释为什么我错误的第一个想法是没有必要添加Write方法?

is there a way to say to Python inside my NDailyLogFile that it shoud have all the methods DailyLogFile that are not defined directly from its mother class? 有没有办法在我的NDailyLogFile中对Python说,它应该有没有直接从其母类定义的所有方法DailyLogFile? So that it prevents this king of error _sync(klass, klass.__dict__[methodName] and that avoid to specify excplicitly ? 这样就可以防止这个错误之王_sync(klass, klass.__dict__[methodName]并避免明确指定?

( original code of DailyLogFile that inspired me it taken from the twisted source here https://github.com/tzuryby/freespeech/blob/master/twisted/python/logfile.py ) (DailyLogFile的原始代码激发了我从扭曲的源代码中获取的信息https://github.com/tzuryby/freespeech/blob/master/twisted/python/logfile.py

EDIT: about using super , i get: 编辑:关于使用super ,我得到:

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

so will not use it. 所以不会用它。 My thoughs was it was right... i must have definitively missed something 我觉得它是对的...我必须明确错过一些东西

There is one workaround, just do: 有一种解决方法,只需:

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

There is a problem here that you are using the class without having instantiated it. 这里存在一个问题,即您在没有实例化的情况下使用该类。 This workaround works because you are forcing to change the class attributes before the instantiation. 此解决方法有效,因为您在实例化之前强制更改类属性。

Another important comment ist that for a subclass of DailyLogFile the command super would not work, since DailyLogFile is a so called "old style class", or "classobj". 另一个重要的评论是,对于DailyLogFile的子类,命令super不起作用,因为DailyLogFile是所谓的“旧样式类”或“classobj”。 The super works for the "new style" classes only. super适用于“新风格”课程。 See this question for further information about this . 有关此问题的详细信息,请参阅此问题

I dare say that the twisted/python/threadable.py code has a bug in it. 我敢说twisted/python/threadable.py代码中有一个bug。 __dict__ only returns the local attributes, not the inherited attributes. __dict__仅返回本地属性,而不返回继承的属性。 Other posts say to use dir() or inspect.getmembers() to get them. 其他 帖子说使用dir()inspect.getmembers()来获取它们。

The good news is that you are correct on your first idea that the write method is inherited. 好消息是你第一次认为write方法是继承的是正确的。 The bad news is that Twisted doesn't recognize inherited methods, so you have to write them yourself. 坏消息是Twisted不承认继承的方法,所以你必须自己编写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM