Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code

Rob Williscroft rtw at freenet.co.uk
Mon Jul 11 19:06:01 EDT 2005


Ralf W. Grosse-Kunstleve wrote in
news:mailman.1622.1121120376.10512.python-list at python.org in
comp.lang.python: 

> Does anyone know if there is a way to hide the _ or self_ from the
> user of the class, i.e. given:
> 
>     class foo(object):
>       @attribute_decorator
>       def __init__(self, x, _y, z):
>          pass
> 
> can we make it such that the user can still write
> 
>     foo(x=1,y=2,z=3)
> 
> without the underscore?
> 

<light-goes-on/> 

Sorry I didn't understand what you ment before:


def init_self( init ):
  class KeywordArgumentError(Exception):
    pass
    
  vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ]
  
  def decorated_init(self, *args, **kw):
    off = 0
    for name in vn:
      if not name.startswith('_'):
          if name in kw:
              value = kw[name]
          else:
              value = args[off]
              off += 1
              
          setattr( self, name, value )
      else:
        off += 1 #was missing (a bug) in last version.
        if name in kw:
          raise KeywordArgumentError(
              "Use %s not %s" % (name[1:],name) 
            )
        if name[1:] in kw:
          kw[name] = kw[name[1:]]
          del kw[name[1:]]
        
    init( self, *args, **kw )
  return decorated_init
              

class MyClass(object):
  @init_self
  def __init__( self, x, _y, z ):
    print "in __init__() _y =", _y

  def show( self ):
    for i in self.__dict__:
      print 'self.%s = %d' %(i,eval('self.%s' % (i,)))

MyClass( 1, 2, 3 ).show()

MyClass( z = 1, x = 2, y = 3 ).show()

MyClass( z = 1, x = 2, _y = 3 ).show()


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/



More information about the Python-list mailing list