Skip to content
Advertisement

Change Python Class attribute dynamically

I have a Class B inheriting Class A with a class attribute cls_attr. And I would like to set dynamically cls_attr in class B. Something like that:

class A():
   cls_attr= 'value'

class B(A):

   def get_cls_val(self):
       if xxx:
          return cls_attr = 'this_value'
       return cls_attr = 'that_value'
   cls_attr = get_cls_val()

I tried several things. I know i might not be looking in the right place but i am out of solutions.

EDIT: Classes are django admin classes

Thanks.

Advertisement

Answer

class attributes can be read on the class or an instance, but you can only set them on the class (trying to set them on an instance will only create an instance attribute that will shadow the class attribute).

If the condition is known at import time, you can just test it in the class body:

xxx = True 

class A(object):
   cls_attr = 'value'

class B(A):
   if xxx:
       cls_attr = 'this_value'
   else
       cls_attr = 'that_value'

Now if you want to change it during the program’s execution, you either have to use a classmethod:

class B(A):
   @classmethod
   def set_cls_attr(cls, xxx):   
       if xxx:
           cls.cls_attr = 'this_value'
       else:
           cls.cls_attr = 'that_value'

or if you need to access your instance during the test:

class B(A):
   def set_cls_attr(self, xxx):   
       cls = type(self)
       if xxx:
           cls.cls_attr = 'this_value'
       else:
           cls.cls_attr = 'that_value'
Advertisement