7

私は自分のバージョンのaを実装しようとしています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'

したがって使用しません。私の考えはそれが正しかった...私は決定的に何かを逃したに違いない

4

2 に答える 2

3

1 つの回避策があります。

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

インスタンス化せずにクラスを使用しているという問題があります。インスタンス化の前にクラス属性を強制的に変更しているため、この回避策は有効です。

別の重要なコメントは、いわゆる「古いスタイルのクラス」または「classobj」であるためDailyLogFile、コマンドのサブクラスでsuperは機能しないことです。DailyLogFilesuper「新しいスタイル」のクラスでのみ機能します。これに関する詳細については、この質問を参照してください

于 2013-06-12T20:50:39.177 に答える
2

twisted/python/threadable.pyコードにはバグがある とあえて言います。__dict__継承された属性ではなく、ローカル属性のみを返します。 他の 投稿では、それらを使用dir()またはinspect.getmembers()取得するように言われています。

良いニュースは、writeメソッドが継承されているという最初の考えが正しいということです。悪いニュースは、Twisted は継承されたメソッドを認識しないため、自分で作成する必要があることです。

于 2013-06-12T20:40:09.047 に答える