Is it possible to create a shortcut ?

Peter Otten __peter__ at web.de
Sat Mar 21 07:29:52 EDT 2009


Stef Mientki wrote:

> I would like to make a shortcut for this:
>     self.Brick.Par [ self.EP[0] ] =
> 
> something like this:
>    self.P[0] =
> 
> 
> is that possible, otherwise than by eval / exec ?

class Brick(object):
    def __init__(self):
        self.Par = [1,2,3]

class P(object):
    def __init__(self, parent):
        self.parent = parent
    def __setitem__(self, index, value):
        p = self.parent
        p.Brick.Par[p.EP[index]] = value

class A(object):
    def __init__(self):
        self.Brick = Brick()
        self.EP = [2,1,0]
        self.P = P(self)

    def demo(self):
        print "before:", self.Brick.Par
        self.P[0] = "shortcut"
        print "after:", self.Brick.Par

a = A()
a.demo()

You can of course simplify things if you move the P.__setitem__() method
into A and drop the helper class P.

Peter



More information about the Python-list mailing list