Following up on
yesterday's fun with objects comparison, I want to share another cool thing I found with Python.
Today's post deals with large objects, and specifically in writing contructor methods. In most languages, your constructor will look like something like this:
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
Working on my super large objects, this could get pretty tedious. I
hate code redundancy. Once again, Python Gods gave me this :
class Foo:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
kwargs is a dictionnary of named arguments. The above constructor will automatically turn them into a set of object attributes. So here's how I would instanciate it:
f = Foo (msg="Hello World", index=1, isItTrue=False)
It will create an object with attributes msg, index and isItTrue. Of course this could require further validation, but if you're working on short scripts and the developer knows what he's doing, this cna be a very powerful construct.
How do you parse your constructor's arguments in your favorite languages ? Show us your code.