2

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.

3
  • Have you seen this answer stackoverflow.com/a/2584050/471899 ? Commented Jun 9, 2015 at 15:12
  • 1
    I think you need to explain the behaviour you want to see more clearly. That is, do you intend for A.cls_attr to change after calling get_cls_val(), or should the change only be seen on B and instances of B. Commented Jun 9, 2015 at 15:28
  • Hi @Dunes, the latter, i want the change only in B. Commented Jun 9, 2015 at 15:47

4 Answers 4

6

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'
Sign up to request clarification or add additional context in comments.

7 Comments

This is the correct answer, and thanks for the suggestions. I need to remember to drink coffee before answering.
Hi I tried your @classmethod solution. It seems that function set_cls_attr in not called...
@jcs Why would it be called if you don't call it ? If you know the value at import time, please check the first part of the answer. Else please try to clarify your question.
@brunodesthuilliers The if part depends on user profile so i need to access 'request' (Django), can't use first part. Yes, i know i have to call the function, that is why i added the cls_attr = get_cls_val() in my example, even though it is not the right way to do it.
@brunodesthuilliers How can i get the function to be executed within the class itself?
|
2

What about using classmethod and polymorphically overriding it in subclass?

class A:
    @classmethod
    def cls_attr(cls):
        return 'value'

class B(A):
    @classmethod
    def cls_attr(cls):
        if cond():
            return 'this'
        else:
            return 'that'

assert A.cls_attr() == 'value'      
cond = lambda: True
assert B.cls_attr() == 'this'
cond = lambda: False
assert B.cls_attr() == 'that'

6 Comments

You should also mention properties, which might be a slightly more elegant-looking solution.
@kirbyfan64sos I've never seen @property with @classmethod. Is it a thing? For instance attributes, sure, but will it work for class attributes / methods?
Properties automatically work without need of being defined as a classmethod.
@ŁukaszR. this will NOT set a class attribute.
@kirbyfan64sos properties don't work when the attribute is looked up on a class - it has to be looked up on an instance. So you couldn't do B.cls_attr, which is kind of the point of having a class attribute at first...
|
0

The easiest solution for me is with property decorator:

class B:
    @property
    def attr_name(self):
        """ do your stuff to define attr_name dynamically """
        return attr_name

Comments

-2

This seems to do what you want:

>>> class B(A):
     @classmethod
     def set_cls_val(cls, x):
             if x == 1:
                     cls.cls_attr = "new"

>>> c = B()
>>> c.cls_attr
'value'
>>> c.set_cls_val(B, 1)
>>> c.cls_attr
'new'
>>> B.cls_attr
'new'

Just set it within the function.

EDIT: Updated to set the class attribute and not the instance attribute, thanks @bruno-desthuilliers.

EDIT: Updates once again, thanks @bruno-desthuilliers. I should think my answers through more clearly. But what you want is answered below.

4 Comments

Wont change the class attribute, sorry.
Fixed sorry. Thanks for that. I had instance and not class.
What's the use of a classmethod if you hard-code the class name ? (hint: the convention for classmethods is to name the first param 'cls' - can you guess why ?)
Still true. It's more so used in metaclassing, and this is a weird situation. It really in this case should be a staticmethod or separate function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.