Loop over some variables of a class in Python -


i know how can loop on variables of class, if want loop on of them?

class myclass:     def __init__(self,var1,var2,var3,var4):         self.var1 = "foo"         self.var2 = "bar"         self.var3 = "spam"         self.var4 = "eggs"  items_to_loop = ("var2","var4") item in items_to_loop:     print(item, myclass.(item)) 

doesn't work. how do this?

first, need understand difference between class, , instance of class (that is, object).

in code, myclass does not contain attributes names var1..var4. however, if create instance of class, instance contain attributes. can access attributes using hasattr check if such attribute exists , getattr find value:

my_object = myclass() attr_name in ('var1', 'var2'):     if hasattr(my_object, attr_name):        print  getattr(my_object, attr_name) 

note classes allowed have attributes, they're declared , behave differently instance attributes:

 class myclass(object):        class_var1 = 'hello'       class_var2 = "goodbye'        def __init__(self, var1, var2):            self.var1 = var1            self.var2 = var2 

now, myclass has singleton attributes class_var1, class_var2 same no matter how many objects of type myclass create, while each 1 of objects have attributes called var1 , var2 , values can different each instance.


Comments

Popular posts from this blog

css - I want to align grid in center -

Contact Form PHP Email Script -

python - SWIG function not printing output -