Skip to content Skip to sidebar Skip to footer

Assigning Class Variable Dynamic Value From Inside A Class

I am trying to dynamically assign a class variable a value from inside of a class. class Test: dynamic_value = get_dynamic_value() I believe get_dynamic_value() should belong to

Solution 1:

Class suites evaluate from top to bottom, and the class you are defining does not exist until after the entire suite is evaluated.

You can put the function definition inside the class body, but you've got to call it after it's been defined, not before. So, this will work:

classTest:

  def get_dynamic_value():
    return'dynamic'

  dynamic_value = get_dynamic_value()

Marking the function as a staticmethod is not necessary; it's not used as a method at all, just a function that is called during the evaluation in the class suite. If you don't want the function to be available after the class is defined (as it isn't intended as a method), you can delete it.

classTest:

  def get_dynamic_value():
    return'dynamic'

  dynamic_value = get_dynamic_value()
  del get_dynamic_value

If the value is really supposed to be dynamically calculated, every time you ask for it (so it is able to change from access to access), then you should use a property.

classTest:@propertydefdynamic_value(self):
    return'dynamic'

This would only be evaluate when accessed on a class instance, but the property object itself would exist on the class.

Solution 2:

Just to add to Matt Anderson's answer - a workaround with class property:

classclassproperty(property):
    def__get__(self, cls, owner):
        returnclassmethod(self.fget).__get__(None, owner)()

classTest:
  @classpropertydefdynamic_value(cls):
    return'dynamic'

And a simple test:

In [102]: Test.dynamic_value
Out[102]: 'dynamic'

Post a Comment for "Assigning Class Variable Dynamic Value From Inside A Class"