I was looking for a long time how to pass an arbitrary number of arguments to __init__ . Here is the solution found:

 class Thing: '''a class with a constructor (or other function) that takes a variable number of arguments and then sets them as class attributes conditionally. ''' def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) door = Thing(size='180x70', color='red chestnut', material='oak') print(door.size, door.color, door.material, sep = ', ') house = Thing(height='23 m', doors=6, rooms=4, material='break') #180x70, red chestnut, oak print(house.height, house.doors, house.rooms, house.material, sep=', ') #23 m, 6, 4, break 

I am sure there is a solution shorter than 2 times, but I can not find it.

  • one
  • What is the question? - FeroxTL
  • the question is: there is a problem - how to transfer to an arbitrary number of arguments for each instance of the class is the solution I give to the problem - def __init __ (self, ** kwargs): for key, value in kwargs.items (): setattr (self, key, value) is the question - is this the right way to do or is there a “better” method? - Oleg
  • 3
    To the question on the link that you specified, there is an answer using self.__dict__.update(kwargs) . It's easier nowhere. - insolor
  • four
    A better method would be not to use one class for such diverse entities, but to inherit from it a separate class for doors, a separate class for houses, etc. But if this is impossible, then use the method that you found. It is foolish to look for a more beautiful implementation for initially wrong design decisions. - Xander

1 answer 1

 class Thing(dict): def __getattr__(self, item): return self[item] 

or

 class Thing: def __init__(self, **kwargs): self.__dict__.update(kwargs)