![](/img/trans.png)
[英]Python is there a difference calling a method from super, or from the class
[英]Python : why a method from super class not seen?
我正在尝试实现我自己的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'
所以我需要显式添加和定义其他方法,如Write
和rotate
方法,如下所示:
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'
所以不会用它。 我觉得它是对的...我必须明确错过一些东西
有一种解决方法,只需:
NDailyLogFile.__dict__ = dict( NDailyLogFile.__dict__.items() + DailyLogFile.__dict__.items() )
threadable.synchronize(NDailyLogFile)
这里存在一个问题,即您在没有实例化的情况下使用该类。 此解决方法有效,因为您在实例化之前强制更改类属性。
另一个重要的评论是,对于DailyLogFile
的子类,命令super
不起作用,因为DailyLogFile
是所谓的“旧样式类”或“classobj”。 super
适用于“新风格”课程。 有关此问题的详细信息,请参阅此问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.