动态更改 Python Class 属性

jcs*_*jcs 2 python class django-admin

我有一个 B 类继承 A 类,类属性 cls_attr。我想在 B 类中动态设置 cls_attr。类似的东西:

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()
Run Code Online (Sandbox Code Playgroud)

我尝试了几件事。我知道我可能没有找对地方,但我没有解决方案。

编辑:类是 django 管理类

谢谢。

bru*_*ers 6

类属性可以在类或实例上读取,但您只能在类上设置它们(尝试在实例上设置它们只会创建一个会影响类属性的实例属性)。

如果在导入时已知条件,则可以在class正文中对其进行测试:

xxx = True 

class A(object):
   cls_attr = 'value'

class B(A):
   if xxx:
       cls_attr = 'this_value'
   else
       cls_attr = 'that_value'
Run Code Online (Sandbox Code Playgroud)

现在,如果您想在程序执行期间更改它,则必须使用classmethod

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

或者如果您需要在测试期间访问您的实例:

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'
Run Code Online (Sandbox Code Playgroud)