[Tutor] best way to dynamically set class variables?

Steven D'Aprano steve at pearwood.info
Wed Nov 7 17:28:09 EST 2018


On Wed, Nov 07, 2018 at 02:48:40PM +0000, Albert-Jan Roskam wrote:

> What is the best way to dynamically set class variables? I am looking 
> for a generalization of something like this:
> 
> class Parent: pass
> class Child(Parent):
>     col1 = 'str'
>     col2 = 'int'

The obvious solution is to do exactly that: just set the class attribute
in the subclass. If the value is dynamically generated, so be it:

class Child(Parent):
    col1 = calculate_some_value()
    col2 = col1 + calculate_something_else()


If the names of the class attributes themselves have to be generated, 
that's what locals() is for:


class Child(Parent):
    for i in range(10):
        name = "column" + str(i)
        locals()[name] = i
    del i

will give you class attributes column0 = 0, column1 = 1, etc. Of course 
you can generate the names any way you like, e.g. read them from a text 
file.

A cleaner solution might be to move the code into a function and pass 
the class namespace to it:


def make_attrs(ns):
    for i in range(10):
        name = "column" + str(i)
        ns[name] = i

class Child(Parent):
    make_attrs(locals())
    assert column0 == 0

assert Child.column1 == 1



Does this help?



-- 
Steve


More information about the Tutor mailing list