A
A
Artyom Innokentiev2015-10-06 11:50:40
Django
Artyom Innokentiev, 2015-10-06 11:50:40

How to overload a class constructor in Python?

Given class:

class Container:
    def __init__(self, a, b, c, d, e, f, g):
        self.a = a
        self.b = b
        self.c = c 
        self.d = d
        self.e = e
        self.f = f
        self.g = g

How to implement constructor overloading?
So the class call would be like this:
obj1 = Container(a=1, b=2, c=3, d=4)
obj2 = Container(x=4, y=3)

My solution is this, but it doesn't work:
class Container:
    def __init__(self, **kwargs):
        for key in kwargs:
            self.key = kwargs[key]

PS Preferably, an implementation with named arguments, but with positional ones is also welcome)
UPD :
There is a function:
def get_data(request):
    a = request.POST['a']
    b = request.POST['b']
    c = request.POST['c']
    d = request.POST['d']
    e = request.POST['e']
    f = request.POST['f']
    cont = Container(a, b, c, d, e, f)
    return cont

It is used to get data from a POST request. I thought it's better to pass data in a class instance than to do return a, b, c, d, e, f . Then, the received data is processed further, for example, it is passed to the function:
I think this is better:
send_data(instanceOfContainer)
And this is worse:
send_data(a, b, c, d, e, f)
The number of fields that are transmitted by the POST request will increase over time and make request.POST[key] a thousand times is not an option. As well as extending the constructor for the Container class with self.x = x . We need a way to make it short and sweet. That's why I'm asking about variable length named and positional parameters.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2015-10-06
@idap

I did this:

class A(object):
    def __init__(self, **kwargs):
        for name, value in kwargs.items():
            setattr(self, name, value)

a = A(x=4, y=5)

D
Dmitry, 2015-10-06
@EvilsInterrupt

There is no such thing as "overload constructor" in Python. There is one __init__ , and to solve the problem with different situations, several methods are made, for example: SuperPuperClass.build_situation1(), SuperPuperClass.build_situation2(). You can read here: Python constructors and __init__

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question