Ron Garret wrote:
>
> Doesn't work for me:
>
> >>> c2
> <__main__.C2 instance at 0x51e850>
> >>> c2.m1()
> G
> >>> class C2:
> ...   __metaclass__ = modify_in_place
> ...   def m1(self): print 'Q'
> ...
> >>> c2.m1()
> G
> >>> C2().m1()
> Q

I assume your original C2 class was defined in a different module, not
in the current global
namespace. What do you get from  c.__class__.__module__ ? It should be
__name__ for
this approach to work.

class C2:
   def m1(self):
      return 'G'

c = C2()

def modify_in_place(name,bases,clsdict):
    cls = globals()[name]
    for attr,val in clsdict.iteritems():
        setattr(cls,attr,val)
    return cls

# Replace second C2 class above with this
class C2:
    __metaclass__ = modify_in_place
    def m1(self):
       return 'Q'

assert c.m1() == 'Q'
assert c.__class__.__module__ == __name__ # make sure c.__class__ is
defined in the current module


     Michele Simionato

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to