python - What is the function of __init__ method here -


class mythread(threading.thread):      def __init__(self,str1,str2):         threading.thread.__init__(self)         self.str1 = str1         self.str2 = str2     def run(self):         run1(self.str1,self.str2) 

i know __init__ used initialize class purpose in next line.is there alternative this?

__init__ used initialize class objects. when create new object of mythread, first calls threading.thread.__init__(self) , defines 2 attributes str1 , str2.

note explicity call threading.thread, base class of mythread. better refer parent __init__ method super(mythread, cls).__init__(self).

python docs

there 2 typical use cases super. in class hierarchy single inheritance, super can used refer parent classes without naming them explicitly, making code more maintainable. use closely parallels use of super in other programming languages.

the second use case support cooperative multiple inheritance in dynamic execution environment.

there couple reasons derived classes calls base classes init. 1 reason if base class special in it's __init__ method. may not aware of that. other reason related oop. let's have base class , 2 subclasses inherits it.

class car(object):     def __init__(self, color):         self.color = color  class sportcar(car):     def __init__(self, color, maxspeed):         super(sportcar, cls).__init__(self, color)         self.maxspeed = maxspeed   class minicar(car):     def __init__(self, color, seats):         super(minicar, cls).__init__(self, color)         self.seats = seats 

this show example, can see how both sportcar , minicar objects calls car class using super(current_class, cls).__init(self, params) run initialize code in base class. note need maintain code in 1 place instead of repeating in every class.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -