default value in __init__

Aaron "Castironpi" Brady castironpi at gmail.com
Sun Oct 12 01:18:23 EDT 2008


On Oct 11, 4:41 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Fri, 10 Oct 2008 06:20:35 -0700, bearophileHUGS wrote:
snip
> > I have seen professional programmers too use class attributes instead of
> > instance ones...
>
> That's only a mistake if you don't mean to use class attributes instead
> of instance attributes.

Off topic: That gives me an idea for an interesting technique.

class Foo( HasInstanceVars ):
    class InstanceVars:
        x= 0
        y= None
        z= [ 0, 1 ]

The __init__ method in HasInstanceVars adds any InstanceVars members
to the instance members.  It's not terribly different than using
__init__-- slightly slower, slightly clearer.  It could even include a
'__initvars__' variable which adds constructor parameters by name to
the instance.  It's marginally problematic how to create new objects
each time Foo is instantiated.  You could require factories, pickle-
unpickle the contents, require 'deepcopy' compatibility, execute a
string, or call a function which uniquely executes the class
statement.

>>> foo= Foo()
>>> foo.x+= 1
>>> foo2= Foo()
>>> foo2.x
0
>>> foo.x
1




More information about the Python-list mailing list