Popular recipes tagged "class"http://code.activestate.com/recipes/tags/class/popular/2017-04-26T17:26:29-07:00ActiveState Code RecipesAuto assign self attributes in __init__ using PEP 484 (Python) 2017-04-26T17:26:29-07:00Ryan Gonzalezhttp://code.activestate.com/recipes/users/4187447/http://code.activestate.com/recipes/580790-auto-assign-self-attributes-in-__init__-using-pep-/ <p style="color: grey"> Python recipe 580790 by <a href="/recipes/users/4187447/">Ryan Gonzalez</a> (<a href="/recipes/tags/annotations/">annotations</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/self/">self</a>, <a href="/recipes/tags/type/">type</a>). Revision 2. </p> <p>TL;DR: Short way of doing stuff like <code>def __init__(self, a, b): self.a = a; self.b = b</code>, using type annotations from PEP 484, inspired by Dart's <code>MyConstructor(this.a, this.b)</code> and Ruby's/Crystal's/(Moon|Coffee)Script's <code>constructor/initialize(@a, @b)</code>.</p> Python 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> Data (A Class For Arbitrary Data) (Python) 2015-08-03T15:22:40-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/579092-data-a-class-for-arbitrary-data/ <p style="color: grey"> Python recipe 579092 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/data/">data</a>, <a href="/recipes/tags/lightweight/">lightweight</a>). </p> <p>A class which is designed to be easy to use when one needs a piece of data with a minimum of source required.</p> <p>Usage:</p> <pre class="prettyprint"><code>shop = Data(owner="Homer", address="down the street", ice=Data(flavor="vanilla", amount=3)) print shop Data: owner = 'Homer' ice = Data: amount = 3 flavor = 'vanilla' address = 'down the street' </code></pre> Find what class an attribute - ie, myObj.myAttr - comes from, and how it's defined (Python) 2012-10-26T12:59:47-07:00Paul Molodowitchhttp://code.activestate.com/recipes/users/4184064/http://code.activestate.com/recipes/578305-find-what-class-an-attribute-ie-myobjmyattr-comes-/ <p style="color: grey"> Python recipe 578305 by <a href="/recipes/users/4184064/">Paul Molodowitch</a> (<a href="/recipes/tags/attribute/">attribute</a>, <a href="/recipes/tags/attributes/">attributes</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/inspection/">inspection</a>, <a href="/recipes/tags/source/">source</a>, <a href="/recipes/tags/__dict__/">__dict__</a>, <a href="/recipes/tags/__getattribute__/">__getattribute__</a>, <a href="/recipes/tags/__getattr__/">__getattr__</a>, <a href="/recipes/tags/__slots__/">__slots__</a>). Revision 3. </p> <p>When inspecting new code (or when debugging), it can be handy to know exactly where a given attribute on an object or class comes from.</p> <p>As a simple example, if you have a class MyClass, you might want to know where MyClass().myMethod is defined.</p> <p>However, things can get tricky when things like __getattr__, __getattribute__, or even compiled objects come into play. That's where this function comes in. It returns what class a given attribute comes from, and what method was used to define it - ie, '__dict__' ('normal' definitions), '__slots__', '__getattr__', '__getattribute__', '(BUILTIN)'.</p> <p>(Note - this function should't be relied on to be 100% accurate - rather, it's a best guess, for where to look to find it. It takes some pretty infrequent edge cases for it to be wrong, though...)</p> DoubleDict (Python) 2012-07-24T21:24:14-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/578224-doubledict/ <p style="color: grey"> Python recipe 578224 by <a href="/recipes/users/2608421/">Stephen Chappell</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/dictionary/">dictionary</a>). </p> <p>After seeing requests for being able to access keys in a dictionary by value, the following recipe was born. It creates the <code>DoubleDict</code> class and allows just that. To ensure that only one key is returned when accessing it by value, values must be unique just as keys are unique, and this rule is automatically enforced. Most dictionary methods are supported, and many more are added to allow working with the dictionary from the view of the values instead of the keys. Several optional metaclasses are also provided to enable optional features in the <code>DoubleDict</code> class such as data consistency checks and atomic method execution.</p> Progress bar class (Python) 2012-08-09T17:39:10-07:00Xavier L.http://code.activestate.com/recipes/users/4171602/http://code.activestate.com/recipes/578228-progress-bar-class/ <p style="color: grey"> Python recipe 578228 by <a href="/recipes/users/4171602/">Xavier L.</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/cli/">cli</a>, <a href="/recipes/tags/curses/">curses</a>, <a href="/recipes/tags/files/">files</a>, <a href="/recipes/tags/module/">module</a>, <a href="/recipes/tags/progress/">progress</a>). Revision 5. </p> <p>See <a href="https://gist.github.com/3306295">gist:3306295</a> for future developments.</p> <p>Here is a little class that lets you present percent complete information in the form of a progress bar using the '=' character to represent completed portions, spaces to represent incomplete portions, '>' to represent the current portion and the actual percent done (rounded to integer) displayed at the end:</p> <p>[===========&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;] 60%</p> <p>When you initialize the class, you specify the minimum number (defaults to 0), the maximum number (defaults to 100), and the desired width of the progress bar. The brackets <code>[]</code> are included in the size of the progress bar, but you must allow for up to 4 characters extra to display the percentage.</p> <p>You'd probably want to use this in conjuction with the curses module, or something like that so you can over-write the same portion of the screen to make your updates 'animated'.</p> CLOS-like around/before/after auxiliary methods (Python) 2011-08-25T22:59:22-07:00Jan Kaliszewskihttp://code.activestate.com/recipes/users/4172762/http://code.activestate.com/recipes/577859-clos-like-aroundbeforeafter-auxiliary-methods/ <p style="color: grey"> Python recipe 577859 by <a href="/recipes/users/4172762/">Jan Kaliszewski</a> (<a href="/recipes/tags/auxiliary/">auxiliary</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/clos/">clos</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/inheritance/">inheritance</a>, <a href="/recipes/tags/method/">method</a>, <a href="/recipes/tags/object/">object</a>, <a href="/recipes/tags/super/">super</a>). </p> <p>This module provides an easy way to define and use your own <strong>around/before/after auxiliary methods</strong>, similar to <a href="http://www.aiai.ed.ac.uk/~jeff/clos-guide.html#meth-comb">those used in CLOS</a> (Common Lisp Object System).</p> Make a Class Available in its Own Definition Body! (Python) 2011-09-15T05:36:36-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577867-make-a-class-available-in-its-own-definition-body/ <p style="color: grey"> Python recipe 577867 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/metaclass/">metaclass</a>). </p> <p>This may sound too good to be true, but see for yourself. No time machines involved. Just plug in this metaclass and look for __newclass__ in your class body. It's not perfect, but the problematic corner cases are more bark than bite.</p> Concrete Class Finder (Python) 2011-08-24T05:29:15-07:00Lucio Santihttp://code.activestate.com/recipes/users/4178886/http://code.activestate.com/recipes/577858-concrete-class-finder/ <p style="color: grey"> Python recipe 577858 by <a href="/recipes/users/4178886/">Lucio Santi</a> (<a href="/recipes/tags/case/">case</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/design/">design</a>, <a href="/recipes/tags/finder/">finder</a>, <a href="/recipes/tags/match/">match</a>, <a href="/recipes/tags/oop/">oop</a>, <a href="/recipes/tags/pattern/">pattern</a>, <a href="/recipes/tags/suitable/">suitable</a>, <a href="/recipes/tags/switch/">switch</a>). </p> <p>This recipe implements a design pattern useful for performing an object-oriented case analysis for a particular object (or a collection of objects as well). Essentially, it is an alternative to complex if-then-else or switches. Modelling each case with a particular class, the Concrete Class Finder searches for an appropriate case/class that applies to the given object/s. Once found, this class can be used in an homogeneous way, independently of the object/s previously considered.</p> Dynamically modifying class attributes at runtime (Python) 2011-03-31T20:07:18-07:00Nabil Stendardohttp://code.activestate.com/recipes/users/4177507/http://code.activestate.com/recipes/577628-dynamically-modifying-class-attributes-at-runtime/ <p style="color: grey"> Python recipe 577628 by <a href="/recipes/users/4177507/">Nabil Stendardo</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/modification/">modification</a>, <a href="/recipes/tags/monkeypatching/">monkeypatching</a>, <a href="/recipes/tags/open/">open</a>). </p> <p>However considered bad programming, Ruby/JavaScript-like open classes (i.e. classes which can be modified at runtime) actually can be a programming pattern when developing plug-in architectures. And, guess what, Python has that functionality too. This code allows to add attributes (typically methods) to classes, even when already instantiated.</p> Make the New Class Available During the Execution of its Body (Python) 2011-08-12T23:44:46-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577744-make-the-new-class-available-during-the-execution-/ <p style="color: grey"> Python recipe 577744 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/metaclass/">metaclass</a>). </p> <p>When a class object is created, normally the class body is exec'ed first and then the class object is generated with that resulting namespace. </p> <p>This recipe lets you flip that around, and then make the class object available to the class body during execution. </p> A flexible state machine class (Python) 2011-05-18T15:17:02-07:00Mike Sweeneyhttp://code.activestate.com/recipes/users/4177990/http://code.activestate.com/recipes/577701-a-flexible-state-machine-class/ <p style="color: grey"> Python recipe 577701 by <a href="/recipes/users/4177990/">Mike Sweeney</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/state_machine/">state_machine</a>). Revision 2. </p> <p>The operation of the state machine is defined by transitions. The transitions control what value is returned and which new state to switch to, given an "event" input when in a certain current "state". State machines have many applications such as games, process controls, and language parsing.</p> Keyword Argument Injection with Python Decorators (Python) 2010-09-05T17:06:04-07:00Ahmet Emre Aladağhttp://code.activestate.com/recipes/users/4174877/http://code.activestate.com/recipes/577382-keyword-argument-injection-with-python-decorators/ <p style="color: grey"> Python recipe 577382 by <a href="/recipes/users/4174877/">Ahmet Emre Aladağ</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/class_decorator/">class_decorator</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/injection/">injection</a>, <a href="/recipes/tags/variable/">variable</a>). Revision 2. </p> <p>In most of the object oriented codes we write, we need to set class attributes to the given argument values and this is a very line-consuming thing. To get over these redundant lines, I found a solution using decorators. </p> Easy property creation and control (Python) 2010-12-01T17:22:49-08:00Kevin L. Sitzehttp://code.activestate.com/recipes/users/4173535/http://code.activestate.com/recipes/577482-easy-property-creation-and-control/ <p style="color: grey"> Python recipe 577482 by <a href="/recipes/users/4173535/">Kevin L. Sitze</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/property/">property</a>, <a href="/recipes/tags/property_creation/">property_creation</a>, <a href="/recipes/tags/tools/">tools</a>, <a href="/recipes/tags/unittests/">unittests</a>). </p> <p>The Property class provides basic functionality that allows class level control over how a particular attribute is managed. In its simplest form a Property attribute works exactly like a regular attribute on an instance while providing documentation details about the attribute accessible via the declaring class.</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> Docstring inheritance class decorator (Python) 2011-11-23T20:12:03-08:00Alec Thomashttp://code.activestate.com/recipes/users/2870300/http://code.activestate.com/recipes/577102-docstring-inheritance-class-decorator/ <p style="color: grey"> Python recipe 577102 by <a href="/recipes/users/2870300/">Alec Thomas</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/docstring/">docstring</a>, <a href="/recipes/tags/inheritance/">inheritance</a>). Revision 2. </p> <p>Inherits method docstrings from parent classes.</p> Alias class attributes (Python) 2009-06-01T01:19:55-07:00Euan Goddardhttp://code.activestate.com/recipes/users/4170559/http://code.activestate.com/recipes/576787-alias-class-attributes/ <p style="color: grey"> Python recipe 576787 by <a href="/recipes/users/4170559/">Euan Goddard</a> (<a href="/recipes/tags/alias/">alias</a>, <a href="/recipes/tags/attribute/">attribute</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/descriptor/">descriptor</a>, <a href="/recipes/tags/metaclass/">metaclass</a>). </p> <p>The alias metaclass allows a declarative way of creating aliases to attributes on a class. The main purpose of which is to adapt classes for duck-typing (see doc-string for me detail).</p> Easy Property Creation in Python (Python) 2009-05-06T11:59:16-07:00runsun panhttp://code.activestate.com/recipes/users/2638612/http://code.activestate.com/recipes/576742-easy-property-creation-in-python/ <p style="color: grey"> Python recipe 576742 by <a href="/recipes/users/2638612/">runsun pan</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/property/">property</a>, <a href="/recipes/tags/property_creation/">property_creation</a>). Revision 4. </p> <p>Presented in this recipe is a function <strong>prop</strong>, with that a property <em>myprop</em> can be created as simple as:</p> <pre class="prettyprint"><code>@prop def myprop(): pass </code></pre> <p>It has only 7 lines of code, easy to understand, easy to customize, will make the code look much netter and will save you a lot of typing.</p> <p>See discussion and the doc test string for more complicated usages.</p> <p>Note: This is a recipe created with python v.2.5.2.</p> 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>