Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to make a bunch of class variables and I would like to do it by looping through a list like that:

vars=('tx','ty','tz') #plus plenty more

class Foo():
    for v in vars:
        setattr(no_idea_what_should_go_here,v,0)

is it possible? I don't want to make them for an instance (using self in the __init__) but as class variables.

share|improve this question
    
Why not to hold them in dict? –  DrTyrsa Nov 29 '11 at 8:15
    
Do you want to share theses variables between different instances? –  luc Nov 29 '11 at 8:17
    
not sure. most likely. the requirement comes from an API and I don't know how they are used in there. –  pawel Nov 29 '11 at 8:28

2 Answers 2

up vote 8 down vote accepted

You can run the insertion code immediately after a class is created:

class Foo():
     ...

vars=('tx', 'ty', 'tz')  # plus plenty more
for v in vars:
    setattr(Foo, v, 0)
share|improve this answer
    
ah. that's cool. I will give it a go and see if the API I work with can handle that. thanks mate! –  pawel Nov 29 '11 at 8:28

If for any reason you can't use Raymond's answer of setting them up after the class creation then perhaps you could use a metaclass:

class MetaFoo(type):
    def __new__(mcs, classname, bases, dictionary):
        for name in dictionary.get('_extra_vars', ()):
            dictionary[name] = 0
        return type.__new__(mcs, classname, bases, dictionary)

class Foo(): # For python 3.x use 'class Foo(metaclass=MetaFoo):'
    __metaclass__=MetaFoo # For Python 2.x only
    _extra_vars = 'tx ty tz'.split()
share|improve this answer
1  
name in for loop clashes with __new__ argument –  uszywieloryba Feb 21 '13 at 12:05
    
@UszyWieloryba thanks, corrected –  Duncan Feb 21 '13 at 14:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.