What is a clean way to declare multiple constructors for one class?
For example, let’s say I have an Item class. One way to create an Item (for example is)
item = Item(product_id, name, description,price)
another way to do the same thing might
item = Item(otherItem)
And then another way to do this.. maybe in some cases I don’t have the price so I want to pass just
item = Item(product_id, name,description)
and yet another case might be
item = Item(product_id,price)
The other question I have is:
There are some private variables which might be initialized during runtime.
Let’s say I have some random variable itemCount and I want to keep a track of it internally.
How do I declare it that I dont have to put it in initialization mode, but rather, somewhere in the run time..
I can do something like
self._count +=1
Thanks
You could use default arguments:
You can substitute in any value you want for
None, if the default value should be something different.Example usage:
For the copy constructor,
item = Item(otherItem), @Raymond’s suggestions of class methods and factory functions may be the most Pythonic way to go.Update: here’s a question about multiple constructors in Python. It also mentions using
*argsand**kwargs.