Popular recipes tagged "subclass"http://code.activestate.com/recipes/tags/subclass/2015-09-29T16:28:46-07:00ActiveState Code RecipesPython add/set attributes to list (Python)
2015-09-29T16:28:46-07:00webby1111http://code.activestate.com/recipes/users/4192908/http://code.activestate.com/recipes/579103-python-addset-attributes-to-list/
<p style="color: grey">
Python
recipe 579103
by <a href="/recipes/users/4192908/">webby1111</a>
(<a href="/recipes/tags/attributes/">attributes</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/dictionary/">dictionary</a>, <a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/subclass/">subclass</a>).
Revision 3.
</p>
<h4 id="python-attribute-listhttpsgithubcomwebby1111python-attribute-list"><a href="https://github.com/webby1111/Python-Attribute-List">Python Attribute List</a></h4>
<p>Add/set attributes to python lists.</p>
<p>A google search for "add attributes to python lists" yields no good stackoverflow answer,
hence the need for this.</p>
<p>Useful for machine learning stuff where you need labeled feature vectors. </p>
<p>This technique can be easily adapted for other built-ins (e.g. int).</p>
<h5 id="the-problem">The Problem</h5>
<pre class="prettyprint"><code>a = [1, 2, 4, 8]
a.x = "Hey!" # AttributeError: 'list' object has no attribute 'x'
</code></pre>
<h5 id="the-solution">The Solution</h5>
<pre class="prettyprint"><code>a = L(1, 2, 4, 8)
a.x = "Hey!"
print a # [1, 2, 4, 8]
print a.x # "Hey!"
print len(a) # 4
# You can also do these:
a = L( 1, 2, 4, 8 , x="Hey!" ) # [1, 2, 4, 8]
a = L( 1, 2, 4, 8 )( x="Hey!" ) # [1, 2, 4, 8]
a = L( [1, 2, 4, 8] , x="Hey!" ) # [1, 2, 4, 8]
a = L( {1, 2, 4, 8} , x="Hey!" ) # [1, 2, 4, 8]
a = L( [2 ** b for b in range(4)] , x="Hey!" ) # [1, 2, 4, 8]
a = L( (2 ** b for b in range(4)) , x="Hey!" ) # [1, 2, 4, 8]
a = L( 2 ** b for b in range(4) )( x="Hey!" ) # [1, 2, 4, 8]
a = L( 2 ) # [2]
</code></pre>
Extending non-extendable C++ based Python classes (Python)
2013-07-18T10:02:59-07:00Ahmet Emre Aladağhttp://code.activestate.com/recipes/users/4174877/http://code.activestate.com/recipes/578576-extending-non-extendable-c-based-python-classes/
<p style="color: grey">
Python
recipe 578576
by <a href="/recipes/users/4174877/">Ahmet Emre Aladağ</a>
(<a href="/recipes/tags/attribute/">attribute</a>, <a href="/recipes/tags/proxy/">proxy</a>, <a href="/recipes/tags/subclass/">subclass</a>).
Revision 2.
</p>
<p>graph_tool library is based on boost C++ library and provides Vertex class binding for Python. If we wanted to extend this Vertex class and add some attributes and methods, it wouldn't let us do that due to private constructor in C++ code (RuntimeError: This class cannot be instantiated from Python). We can overcome this obstacle using Proxy pattern.</p>
<p>In the __getattr__ method, if the attribute(or function name) is not in the Subclass MyVertex, then it looks for attributes of Vertex object that is defined inside MyVertex.</p>
Abstract method decorator (Python)
2011-04-20T21:50:23-07:00jimmy2timeshttp://code.activestate.com/recipes/users/4177690/http://code.activestate.com/recipes/577666-abstract-method-decorator/
<p style="color: grey">
Python
recipe 577666
by <a href="/recipes/users/4177690/">jimmy2times</a>
(<a href="/recipes/tags/abstract/">abstract</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/inheritance/">inheritance</a>, <a href="/recipes/tags/method/">method</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/subclass/">subclass</a>).
Revision 5.
</p>
<p>A simple decorator that helps define abstract methods: when such a method is called, an appropriate exception is raised.</p>
List with fast membership test (__contains__) (Python)
2010-04-18T05:52:57-07:00Paul Bohmhttp://code.activestate.com/recipes/users/4173615/http://code.activestate.com/recipes/577185-list-with-fast-membership-test-__contains__/
<p style="color: grey">
Python
recipe 577185
by <a href="/recipes/users/4173615/">Paul Bohm</a>
(<a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/subclass/">subclass</a>).
Revision 3.
</p>
<p>Just a list subclass with a fast hash based __contains__ provided by a Set. Inheriting from list was far more work than I had anticipated AND the code below is still buggy.</p>
<p>Still, this provides O(1) indexed access and O(1) contains. If you use this expect the slicing code to be broken despite the attempts to get it right. Fixes graciously accepted!</p>
Find all subclasses of a given class (Python)
2009-11-04T20:26:08-08:00Gabriel Genellinahttp://code.activestate.com/recipes/users/924636/http://code.activestate.com/recipes/576949-find-all-subclasses-of-a-given-class/
<p style="color: grey">
Python
recipe 576949
by <a href="/recipes/users/924636/">Gabriel Genellina</a>
(<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/extending/">extending</a>, <a href="/recipes/tags/inheritance/">inheritance</a>, <a href="/recipes/tags/plugin/">plugin</a>, <a href="/recipes/tags/subclass/">subclass</a>, <a href="/recipes/tags/subclasses/">subclasses</a>, <a href="/recipes/tags/type/">type</a>).
Revision 3.
</p>
<p>itersubclasses(cls) returns a generator over all subclasses of cls, in depth first order. cls must be a new-style class; old-style classes are <em>not</em> supported.</p>
Method-based URL dispatcher for the Tornado web server (Python)
2009-11-20T11:51:47-08:00Dan McDougallhttp://code.activestate.com/recipes/users/4169722/http://code.activestate.com/recipes/576958-method-based-url-dispatcher-for-the-tornado-web-se/
<p style="color: grey">
Python
recipe 576958
by <a href="/recipes/users/4169722/">Dan McDougall</a>
(<a href="/recipes/tags/dispatcher/">dispatcher</a>, <a href="/recipes/tags/shortcuts/">shortcuts</a>, <a href="/recipes/tags/subclass/">subclass</a>, <a href="/recipes/tags/tornado/">tornado</a>, <a href="/recipes/tags/url/">url</a>, <a href="/recipes/tags/web/">web</a>).
Revision 5.
</p>
<p>The MethodDispatcher is a subclass of <a href="http://www.tornadoweb.org/">tornado</a>.web.RequestHandler that will use
the methods contained in subclasses of MethodDispatcher to handle requests. In
other words, instead of having to make a new RequestHandler class for every URL
in your application you can subclass MethodDispatcher and use the methods
contained therein <em>as</em> your URLs.</p>
<p>The MethodDispatcher also adds the convenience of automatically passing
arguments to your class methods. So there is no need to use Tornado's
get_argument() method.</p>
<h5><strong>Example</strong></h5>
<p>To demonstrate the advantages of using MethodDispatcher I'll present a standard
Tornado app with multiple URLs and re-write it using MethodDispatcher...</p>
<h5><strong>The standard Tornado way</strong></h5>
<pre class="prettyprint"><code>class Foo(tornado.web.RequestHandler):
def get(self):
self.write('foo')
class Bar(tornado.web.RequestHandler):
def get(self):
self.write('bar')
class SimonSays(tornado.web.RequestHandler):
def get(self):
say = self.get_argument("say")
self.write('Simon says, %s' % `say`)
application = tornado.web.Application([
(r"/foo", Foo),
(r"/bar", Bar),
(r"/simonsays", SimonSays),
])
</code></pre>
<h5><strong>The MethodDispatcher way</strong></h5>
<pre class="prettyprint"><code>class FooBar(MethodDispatcher):
def foo(self):
self.write("foo")
def bar(self):
self.write("bar")
def simonsays(self, say):
self.write("Simon Says, %s" % `say`)
application = tornado.web.Application([
(r"/.*", FooBar)
])
</code></pre>
<h5><strong>Notes</strong></h5>
<p>As you can see from the above example, using the MethodDispatcher can
significantly reduce the complexity of Tornado applications. Here's some other
things to keep in mind when using the MethodDispatcher:</p>
<ul>
<li>MethodDispatcher will ignore any methods that begin with an underscore (_).
This prevents builtins and private methods from being exposed to the web.</li>
<li>The '/' path is special: It always maps to self.index().</li>
<li>MethodDispatcher does not require that your methods distinquish between GET
and POST requests. Whether a GET or POST is performed the matching method
will be called with any passed arguments or POSTed data. Because of the way
this works you should not use get() and post() in your MethodDispatcher
subclasses unless you want to override this functionality.</li>
<li>When an argument is passed with a single value (/simonsays?say=hello) the
value passed to the argument will be de-listed. In other words, it will be
passed to your method like so: {'say': 'hello'}. This overrides the
default Tornado behavior which would return the value as a list:
{'say': ['hello']}. If more than one value is passed MethodDispatcher will
use the default behavior.</li>
</ul>
Subclass function (Python)
2009-03-23T00:48:54-07:00Peter Russellhttp://code.activestate.com/recipes/users/4166045/http://code.activestate.com/recipes/576697-subclass-function/
<p style="color: grey">
Python
recipe 576697
by <a href="/recipes/users/4166045/">Peter Russell</a>
(<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/metaprogramming/">metaprogramming</a>, <a href="/recipes/tags/subclass/">subclass</a>).
Revision 4.
</p>
<p><strong>Do not use this function - instead use the built in type(name, bases, dict) constructor</strong> This is a function that builds a subclass of some base classes. I wrote it while unaware that type could be used as a constructor.</p>
User List Subclass (Python)
2008-08-18T09:26:07-07:00nosklohttp://code.activestate.com/recipes/users/4166478/http://code.activestate.com/recipes/576428-user-list-subclass/
<p style="color: grey">
Python
recipe 576428
by <a href="/recipes/users/4166478/">nosklo</a>
(<a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/slices/">slices</a>, <a href="/recipes/tags/subclass/">subclass</a>, <a href="/recipes/tags/__getitem__/">__getitem__</a>).
Revision 2.
</p>
<p>As subclassing list has a problem when using __getitem__, __delitem__ and __setitem__ methods with slices (they don't get called because parent implements __getslice__, __delslice__ and __setslice__ respectively), I've coded this UserList class that is a subclass of list, but overwrites these methods.
By subclassing this class, you can overwrite __getitem__ and it will be called correctly for slices.</p>