Class's metafunction problem

Gregor Mirai gregmi at email.si
Fri Oct 18 07:24:15 EDT 2002


Is it possible that a class would have a member function, that could change
his variables (class variables) ? Here I am not referring to instance
variables.

Classes are also objects, so I would like to define member functions that
could act on them and thus effectively changing their definition
(metaclasses).

Is there any elegant way to solve the problem ? What follows are some not
very elegant attempts at the problem :

One ugly way to do it (because one has to pass an instance to a function
call).

class A:
    a=0
    def  change(self, x):
        A.a = x

>>> obj=A()
>>> obj.a
0
>>> A.change(A(), 3)
>>> obj.a
3

Two classes way (not good, because I need two classes :)).

class A:
   a=0

class chA:
   def change(self, x):
      A.a = x

>>> obj=A()
>>> obj.a
0
>>> ch=chA()
>>> ch.change(3)
>>> obj.a
3

Direct way (not very user friendly):

class A:
   a = 0
   def change(x):
      A.a = x

>>> obj=A()
>>> obj.a
0
>>> A.__dict__["change"](3)
>>> obj.a
3


Best regards,
Greg





More information about the Python-list mailing list