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



Ralf W. Grosse-Kunstleve wrote in
news:mailman.1622.1121120376.10512.python-list@xxxxxxxxxx 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/
.



Relevant Pages

  • Re: best cumulative sum
    ... Alan ... def ireduce: ... if init is None: ... Prev by Date: ...
    (comp.lang.python)
  • Re: Ordered Sets
    ... to store the key itself in the Node or the list. ... script that stores only prev and next. ... def discard: ... yield start ...
    (comp.lang.python)
  • Re: What about a series type?
    ... On 6/7/07, Robert Dober wrote: ... > def initialize ... > @init = init ... puts s1.get_some ...
    (comp.lang.ruby)
  • Re: What about a series type?
    ... def initialize ... @init = init ... puts s1.get_some ...
    (comp.lang.ruby)
  • Re: Creating new types and invoking super
    ... def _init: ... return _init ... This kind of approach can't work, you need to call super(A, obj). ... -- Guilherme H. Polo Goncalves ...
    (comp.lang.python)