[Tutor] best way to dynamically set class variables?
Mats Wichmann
mats at wichmann.us
Wed Nov 7 14:36:40 EST 2018
Not sure what you're after, but what's wrong with just setting them?
Parent.avar = "a class var"
On November 7, 2018 7:48:40 AM MST, Albert-Jan Roskam <sjeik_appie at hotmail.com> wrote:
>Hi,
>
>Background: In my code I use sqlalchemy to read SQL server data. I want
>to write that data to HDF5 using pytables (see 'declaring a column
>descriptor': https://www.pytables.org/usersguide/tutorials.html). My
>question is not about pytables or sqlalchemy per se, but I thought it
>would be informative to mention this.
>
>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'
>
>Several (im)possible solutions:
>
># -------
>class Parent: pass
>class_vars = dict(col1='str', col2='int')
>
># approach 1
>Child = type('Child', (Parent,), class_vars)
>
># approach 2
>class Child(Parent): pass
>Child.__dict__.update( class_vars ) # AttributeError: 'mappingproxy'
>object has no attribute 'update'
>
># approach 3
>class Child(Parent): pass
>for k, v in class_vars.items():
> setattr(Child, k, v)
>
>I initially chose approach #1, but I find this way of defining a class
>quite cryptic (but then, it's part of the language definition!). What's
>the best way to do this? I am using Python 3.5 (Windows). Thanks in
>advance!
>
>Best wishes,
>Albert-Jan
>_______________________________________________
>Tutor maillist - Tutor at python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor
--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
More information about the Tutor
mailing list