class closure question

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Jan 17 17:10:48 CET 2008


Steven W. Orr a écrit :
> I want to indirectly change the value of a variable.
> 

Are you sure this is the correct formulation of your problem ?

> #! /usr/bin/python
> foo = [44]
> bar = foo
> bar[0] = 55
> print 'bar = ', bar
> print 'foo = ', foo
> 
> This works fine.
> 
> bar =  [55]
> foo =  [55]
> 
> But I want to do the same with a class value.
> 
> #! /usr/bin/python
> S = None
> dd = { 'class': [S] }
> class C1(object):
>     def __init__(self):
>         print 'Hello from C1'
> 
> def mkclass(base):
>     class zzz(base):
>         pass
>     return zzz
> 
> dd['class'][0] = mkclass( C1 )

Hem... If your goal is to rebind S, then you got it all wrong. What 
you're doing here is to rebind dd['class'][0] from S to the return value 
of mkclass. This won't of course rebind S itself.

> print "dd['class'][0].__bases__ = ", dd['class'][0].__bases__
> print 'S = ', S
> 
> The answer is not what I want:
> 
> dd['class'][0].__bases__ =  (<class '__main__.C1'>,)
> S =  None
> 
> The goal is for S to be set to the returned class from mkclass.

Seems like you still don't get how Python's assignment work.

FWIW, the type of object you want to bind to S is totally irrelevant, so 
you could get rid of this mkclass stuff for the moment. Also, you don't 
have to make dd['class'] point to a list containing S here - dicts are 
themselves mutables, so your example would work the same with

   dd = {'class':S}

and
   dd['class'] = any_other_object;


> Can someone help?

Not me, at least unless you explain your real use case - I mean, the 
problem you're trying to solve by "indirectly chang(ing) the value of a 
variable".



More information about the Python-list mailing list