[Tutor] best way to dynamically set class variables?

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Nov 7 17:32:33 EST 2018


On Wed, 7 Nov 2018 at 18:35, Alan Gauld via Tutor <tutor at python.org> wrote:
>
> On 07/11/2018 14:48, Albert-Jan Roskam wrote:
>
> > What is the best way to dynamically set class variables?
>
> I think I'm maybe missing the point of your question?

I think you are as well :)

IIUC then the question is: how can I programatically/dynamically
create a class that has some attributes derived from data that is
known at runtime?

Am I understanding this correctly Albert?

> > # -------
> > class Parent: pass
> > class_vars = dict(col1='str', col2='int')
> >
> > # approach 1
> > Child = type('Child', (Parent,), class_vars)

This seems fine to me. It may seem cryptic but that's only because
it's unusual to do this. You are creating a "type" and that is the
constructor for type objects.

--
Oscar


More information about the Tutor mailing list