Python : why a method from super class not seen?

2024/9/28 5:23:38

i am trying to implement my own version of a DailyLogFile

from twisted.python.logfile import DailyLogFileclass 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 = rotateAfterNdef 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 statethreadable.synchronize(NDailyLogFile)

but it looks like i miss a fundamental of Python subclassing process...as i get this error :

Traceback (most recent call last):File "/home/twistedtestproxy04.py", line 88, in <module>import ndailylogfileFile "/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 synchronizesync = _sync(klass, klass.__dict__[methodName])
KeyError: 'write'

so i need to explicitly add and define others methods like Write and rotate method like this:

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?

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? So that it prevents this king of error _sync(klass, klass.__dict__[methodName] and that avoid to specify excplicitly ?

( 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 )

EDIT: about using super, i get:

  File "/home/lt/inwork/ndailylogfile.py", line 57, in writesuper.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

Answer

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". The super works for the "new style" classes only. See this question for further information about this.

https://en.xdnf.cn/q/71374.html

Related Q&A

Extract features from last hidden layer Pytorch Resnet18

I am implementing an image classifier using the Oxford Pet dataset with the pre-trained Resnet18 CNN. The dataset consists of 37 categories with ~200 images in each of them. Rather than using the final…

Python Graphs: Latex Math rendering of node labels

I am using the following code to create a pygraphviz graph. But is it possible to make it render latex math equations (see Figure 1)? If not, is there an alternative python library that plots similar…

Given general 3D plane equation

Lets say I have a 3D plane equation:ax+by+cz=dHow can I plot this in python matplotlib?I saw some examples using plot_surface, but it accepts x,y,z values as 2D array. I dont understand how can I conv…

Spark-submit fails to import SparkContext

Im running Spark 1.4.1 on my local Mac laptop and am able to use pyspark interactively without any issues. Spark was installed through Homebrew and Im using Anaconda Python. However, as soon as I try…

Is there a Python API for event-driven Kafka consumer?

I have been trying to build a Flask app that has Kafka as the only interface. For this reason, I want have a Kafka consumer that is triggered when there is new message in the stream of the concerned to…

SWIG python initialise a pointer to NULL

Is it possible to initialise a ptr to NULL from the python side when dealing with SWIG module?For example, say I have wrapped a struct track_t in a swig module m (_m.so), I can create a pointer to the…

Replacing punctuation in a data frame based on punctuation list [duplicate]

This question already has answers here:Fast punctuation removal with pandas(4 answers)Closed 5 years ago.Using Canopy and Pandas, I have data frame a which is defined by:a=pd.read_csv(text.txt)df=pd.Da…

How to import one submodule from different submodule? [duplicate]

This question already has answers here:Relative imports for the billionth time(14 answers)Closed 6 years ago.My project has the following structure:DSTC/st/__init__.pya.pyg.pytb.pydstc.pyHere is a.py i…

How to add dimension to a tensor using Tensorflow

I have method reformat in which using numpy I convert a label(256,) to label(256,2) shape. Now I want to do same operation on a Tensor with shape (256,)My code looks like this (num_labels=2) :--def ref…

Down arrow symbol in matplotlib

I would like to create a plot where some of the points have a downward pointing arrow (see image below). In Astronomy this illustrates that the true value is actually lower than whats measured.Note tha…