user4183320
user4183320

Reputation:

How to use *args and **kwargs with __init__ in a smart and elegant way in Python?

From docu and from some tutorials I know the basics about *args and **kwargs. But I think about how to use them with __init__ in a nice and pythonic way. I added this pseudo code to describe the needs. __init__() should behave like this:

In other languages (e.g. C++) I just would overload the constructor. But now with Python I don't know how to implement this in one function.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Foo:
    def __init__(self, *args, **kwargs):

    # if type() of parameter == type(self)
        # duplicate it

    # else
        # init all members with the parameters
        # e.g.
        # self.name = name

# explicite use of the members
f = Foo(name='Doe', age=33)
# duplicate the object (but no copy())
v = Foo(f)
# this should raise an error or default values should be used
err = Foo()

I am not sure if the solution would be different between Python2 and 3. So if there is a difference please let me know. I will change the tag to Python3.

Upvotes: 1

Views: 492

Answers (1)

glglgl
glglgl

Reputation: 91059

You could just describe what you wrote in text. That is,

def __init__(self, *args, **kwargs):
    if len(args) == 1 and not kwargs and isinstance(args[0], type(self)):
        other = args[0]
        # copy whatever is needed from there, e. g.
        self.__dict__ = dict(other.__dict__) # copy it!
    else:
        self.__dict__ = kwargs
        # what do we do with args here?

Upvotes: 1

Related Questions