Note that there are some explanatory texts on larger screens.

plurals
  1. PORedirect calls to a member of a class in python
    text
    copied!<p>I was trying to 'extend' a closed class</p> <pre><code>collections.defaultdict(lambda: 1) </code></pre> <p>by addint it 2 methods, called 'vocabulary', and 'wordcount' apparently it's impossible to setattr method to builin types, nor can I inherit from defaultdic, so I decided to write a class and redirect calls to it to the type I want to extend.</p> <pre><code>class BagOfWordDoc(): def __init__(self): self.data = collections.defaultdict(lambda: 1) for method in dir(self.data): if hasattr(getattr(self.data, method),'__call__') and method not in ['__class__', '__self__']: l = lambda *args: getattr(self.data, method)(*args) setattr(self, method,l) def vocabulary(self): return self.data.keys() def wordcount(self): return reduce(operator.add, self.data.values(), 0) </code></pre> <p>However it shows upon accessing it</p> <pre><code> doc = BagOfWordDoc() doc[123] = 123 # yields TypeError: values() takes no arguments (1 given) doc.keys() # yields TypeError: values() takes no arguments (1 given) doc.xxx() # yields TypeError: values() takes no arguments (1 given) </code></pre> <p>So it'is as if every lambda was mapped to the 'values' function And 'values' is the last element of the property list</p> <p>Do you know why this happens ? As for the initial problem, I am now thinking of rewriting my own defaultdict.</p> <h2>update</h2> <p>Based on the suggestion made, hereis the working implementation :</p> <pre><code>class BagOfWordDoc(): def __init__(self): self.data = collections.defaultdict(lambda: 0) def __getattr__(self, *args): return self.data.__getattribute__(*args) def vocabulary(self): return self.data.keys() def wordcount(self): return reduce(operator.add, self.data.values(), 0) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload