trollpidor
trollpidor

Reputation: 477

Python. Did I understand the code correctly?

I have a little question. Does this piece of code means: "whenever an instance of the class MyThread created, initialize threading.Thread constructor and assign passed arguments to variables inside MyThread class". Essentially what this class does is it creates an instance of threading.Thread class AND adds a little bit of custom functionality, such as new variables. Right?

class MyThread(threading.Thread):
      def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

If I am correct, this piece of code

class MyThread(threading.Thread):
          def __init__(self):
            threading.Thread.__init__(self)

simply creates an instance of threading.Thread class and in fact the same can be done by simply putting a = threading.Thread(). Correct?

Upvotes: 2

Views: 88

Answers (2)

Omar
Omar

Reputation: 56

That part of the code is not creating an instance of threading.Thread. The code is declaring a class that is a subclass (or specialization) of threading.Thread(), that is, when you make an instance of MyThread it will be a threading.Thread itself. threading.Thread.__init__(self) is just initializing the class instance as a threading.Thread by calling that class constructor, that is commonly done with super(MyThread, self).__init__() when using new style classes.

Doing a = threading.Thread() is just creating an instance of the Thread class, nothing more.

Upvotes: 0

Messa
Messa

Reputation: 25181

Yes.

class MyCls(BaseCls):
    def __init__(self):
        BaseCls.__init__(self)

is the same as

class MyCls(BaseCls):
    pass # constructor not overriden

BaseCls constructor will be called in both cases when creating MyCls objects.

MyCls (when "empty") and BaseCls are still different things, there will be some differences if for example BaseCls uses __slots__.

Upvotes: 1

Related Questions