GuySoft
GuySoft

Reputation: 1723

How to overload the __init__ function of the Thread class in python3?


I am trying to port to python3 this answer. But I am not sure how to set theThread.__init__ function in python3.

The deceleration of a python2 Thread.__init__ in a thread class is:

Thread.__init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None)

But python3 its:

Thread.__init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)

Note: The ending in python3 is: args=(), kwargs=None, *, daemon=None) Part of the problem is I don't understand how to treat the asterisk * in the function deceleration. Explaining what it is for would also be helpful.

Just using the python2 raises: TypeError: __init__() takes from 1 to 6 positional arguments but 7 were given

How should I write the python3 Thread.__init__?

Update, the python2 call in the example is:

Thread.__init__(self, group, target, name, args, kwargs, Verbose)

How so my logic would say this would work in python3, but it doesn't, the answer should include how to call this, or instructions how to build it, including kwargs:

Thread.__init__(self, group, target, name, args, kwargs, daemon)

Upvotes: 3

Views: 1251

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160617

If you need to overload it, just be careful how you construct your super call (or any call up to Thread.__init__) to be explicit about the arguments after the bare * (i.e provide them in key form):

For example, if you have a Foo class with a signature of:

class Foo:
    def __init__(self, b=30, *, c=40):
        print(b, c)

you'd need to provide a c=<value> argument whenever you invoke it. So, for example, if you overload it in a FooChild class by:

class FooChild(Foo):
    def __init__(self, a, myval_1, my_val2):
        print(a)
        super().__init__(b, c=my_val2)

you'll need to provide the name c when calling BaseClass.__init__.

If you have *args and **kwargs you'll again just need to explicitly provide a value for c when invoking the child class __init__, i.e:

class FooBase(Foo):
    def __init__(self, a, *args, **kwargs):
        print(a)
        super().__init__(*args, **kwargs)

Can be invoked by FooBase(1, 2, c=30) but not like FooBase(1, 2, d=30) or FooBase(1, 2, 30). You need to pass c to __init__, it requires it.

Upvotes: 1

Related Questions