Tuesday, 15 March 2011

oop - Instantiate an instance of a class with unknown number of attributes in Python 3 -



oop - Instantiate an instance of a class with unknown number of attributes in Python 3 -

how can create instance of object (which may have many, 20 ) attributes, without specifying default values attributes?

for instance, lets have

class thing: def __init__(self, att1, att2, att3, etc....): self.att1 = att1 self.att2 = att2 self.att3 = att3 etc

i can say,

first_thing = thing() first_thing.att1 = 33

but, if have 30 attributes, not want specify self.att = att every single one. there way out of that? instance, let's later added attribute , din't want have go , add together __init__ function, or did not want declare 30 values when creating instance of object - there way this?

you can take variable of arguments * form, this

def __init__(self, *args): ...

and then, can create new variables this

def __init__(self, *args): idx, item in enumerate(args): setattr(self, "attr{}".format(idx), item)

python oop

No comments:

Post a Comment