[Tutor] best way to dynamically set class variables?

Alan Gauld alan.gauld at yahoo.co.uk
Wed Nov 7 13:33:20 EST 2018


On 07/11/2018 14:48, Albert-Jan Roskam wrote:

> What is the best way to dynamically set class variables? 

Remember the golden rule of OOP is that objects(and classes)
should do it to themselves. Ideally the class variables
should be there to support some kind of class behaviour
and that behaviour should set the variables. (Reading is
arguably different, it's usually OK for external objects
to "grab a value" from a class. But if you are modifying
it from outside then who is doing what and should that
"what" not be done by the class (maybe in a class method)?

Having said that, if you can find a valid scenario where
objects/functions outside the class need to modify the
internals of the class directly then directly is how
they should do it.

class C:
   classvar = 'foo'

x = C.classvar      # read directly
C.classvar = 'bar'  # assign directly

I am looking for a generalization of something like this:
> 
> class Parent: pass
> class Child(Parent):
>     col1 = 'str'
>     col2 = 'int'

What's not general about that?
I think I'm maybe missing the point of your question?

> # -------
> 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)

That all seems incredibly complicated and I'm not
sure what it would buy you over direct assignment?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list