Python Interview-override & Overload

Source: Internet
Author: User

Let's first say overload overload.


In Java, overloading is supported, overloading means the ability to define methods with the same method name, the number of arguments passed in the method, or different types of parameters. Like what:

int mymethod (int a, int b) int mymethod (int num)

float MyMethod (int A, float b) float mymethod (float var1, int var2)

int mymethod (int a, int b) int MyMethod (float var1, float var2)

The following example is wrong, because the number of arguments passed in is the same, the type is the same, just giving a different name does not change the specific method.

int mymethod (int a, int b, float c) int mymethod (int var1, int var2, float var3)

So for Python, we can also write such a method, for example, why Python does not support overload

def sum (A, B):   return a+bdef sum (a,b,c):   return A+b+c

The above method, if Python supports overload, when we run two different sum methods, we get different results.

Print sum print sum (resulttypeerror:sum) # takes exactly 3 arguments (2 given)

When we want to invoke the first sum method, we make an error. This is because Python does not support overload, and a second method with the same name overrides the overwrite first method.

So, when we want to use similar overload techniques in Python, more of us will use

Default argument values

def ask_ok (prompt, retries=4, complaint= ' Yes or No, please! ')
You can call this method and pass in a different number of arguments

ASK_OK (' Does really want to quit? ') ASK_OK (' OK to overwrite the file? ', 2) ask_ok (' OK to overwrite the file? ', 2, ' Come on, only yes or no! ')

Keyword arguments

def parrot (Voltage, state= ' a stiff ', action= ' voom ', type= ' Norwegian Blue '):
If you use the keyword assignment, you do not need to pass in the parameters in order

Parrot (+)                                          # 1 positional argumentparrot (voltage=1000)                                  # 1 keyword argumentparrot (voltage=1000000, action= ' Vooooom ')             # 2 keyword argumentsparrot (action= ' vooooom ', voltage=1000000)             # 2 keyword Argumentsparrot (' A  Million ', ' bereft of life ', ' jump ')         # 3 positional argumentsparrot (' A Thousand ', state= ' pushing up the Daisies ')  # 1 positional, 1 keyword

Arbitrary argument lists

def write_multiple_items (file, separator, *args):    file.write (Separator.join (args))


############################################################################################################### #####################


We went on to say that the override of Python overrides

In Java, we use the extends parent class method to inherit, inherit the method of the parent class, and override the contents of the method. You can also call the parent class's method with the Super keyword.

Python can do the same thing, no extends, there is super.

Class Parent (object):    def myMethod (self):        print ' Calling-parent method ' class child (parent):    def myMethod ( Self):        print ' calling child method ' P = parent () P.mymethod () c = Child () C.mymethod () # resultcalling Parent Methodcalling Child method

Child inherits the parent class and overrides the MyMethod method. Of course, you can not inherit the MyMethod method, write your own method.

But after inheriting, you can use the Super keyword to invoke the parent class's method

Class Parent (object):    def myMethod (self):        print ' Calling-parent method ' class child (parent):    def Childmethod (self):        print ' calling child method '        super (Child, self). MyMethod () p = Parent () p.mymethod () c = Child () C.childmethod () # resultcalling parent methodcalling Child Methodcalling Parent method

The same code, adding the Super keyword, is tantamount to calling the Childmethod method, and then calling the parent class's MyMethod method.


############################################################################################################### #####################


Extended


1: The construction of the base class in inheritance (The __init__ () method) is not automatically called, it needs to be called specifically in the construction of its derived class. different from C #
2: When calling a method of the base class, you need to prefix the class name of the base class with the Self argument variable. Unlike calling a normal function in a class, you do not need to take the self argument
3:python always looks for a method of the corresponding type first, and if it cannot find the corresponding method in the derived class, it begins to look in the base class one by one. (Find the method that was called in this class before you can find it in the base class).

Class baseclass:    def __init__ (self, name, age):        self.name = name    &nbs P   Self.age = age        print "BaseClass is inited"     def speak (self, name):  &NB Sp     PRINT "base class is speaking:%s"% Nameclass subclass (BaseClass):    def __init__ (self, name, AG E, salary):        baseclass.__init__ (self, Name, age) # Call the parent function remember to bring self, the difference between ordinary calls does not require self    & nbsp   self.salary=salary        print "Subclass is inited and the salary is:%s"% self.salary    Def talk (self, sth):        print "%s talking:%s"% (Self.name, STH)       &NBSP ; Baseclass.speak (self, sth) <span style= "font-family:arial, Helvetica, Sans-serif;" ># Call the parent class function remember to bring self, the difference between ordinary calls does not need self</span>if (__name__== "__main__"):    S=subclass ("Joan", 1,800)     S.talk ("A Story") # Resultbaseclass is initedSubclass is inited and the salary Is:800joan Talking:a Storybase class are speaking:a story 

If the subclass does not have a __init__ initialization function, the subclass inherits the properties of the parent class

Class BaseClass:    def __init__ (self, Name, age):        self.name = name        Self.age = Age        print "BaseClass is Inite D "    def speak (self, name):        print" base class is speaking:%s "% Nameclass subclass (BaseClass):    #def __init__ (s Elf, name, age, Salary):    #    baseclass.__init__ (self, name, age)    #    self.salary=salary    #    Print "Subclass is inited and the salary are:%s"% self.salary    def talk (self, sth):        print "%s talking:%s, he a GE is%d "% (Self.name, STH, Self.age)        baseclass.speak (self, STH) if (__name__==" __main__ "):    s=subclass (" Joan ", 1) # when initialized, the Init method is called first in this class, without invoking the parent class's    S.talk (" a Story ")    S.speak (" Directly use BaseClass function ") # By calling the Speak method from the subclass, it will be found in the subclass, find it directly, and will find the call in the parent class # Resultbaseclass is Initedjoan talking:a story, he is the 1base class is SPE Aking:a Storybase class is speaking:directly use BaseClass function

After we have annotated the __init__ method of the subclass, we inherit the properties of the parent class.


Multiple inheritance

Class P1 # (Object):    def foo (self):                  print ' P1-foo '  class P2 # (Object):    def foo (self):        print ' P2-foo '    def bar:        print ' P2-bar '  class C1 (P1,P2):    Pass   class C2 (P1,P2):    def bar (self) :        print ' C2-bar '    class D (C1,C2):    

Notice in the above code that we annotated class inherits object, which belongs to the classic class, we call the function

D = d () D.foo () D.bar () # Resultp1-foop2-bar

When instance D calls Foo (), the search order is d = = C1 = P1

When instance D calls bar (), the search order is d = C1 = P1 = P2

In other words, the classic class searches for attributes in the "left-to-right, depth-first" way. D First look for whether it has the Foo method, no find the nearest parent class C1 the method, if not, continue to look up until the method is found in P1, find the end.



When we cancel the comment of object, we run the same code.

Class P1 (object): Def foo (self): print ' P1-foo ' class P2 (object): Def foo (self): print ' P2-foo ' def Bar    (self): print ' P2-bar ' class C1 (P1,P2): Passclass C2 (P1,P2): Def bar (self): print ' C2-bar ' class D (C1,C2): PASSD = d () D.foo () D.bar () print "MRO:", [x.__name__ for X in d.__mro__]# RESULTP1-FOOC2-BARMRO: [' d ', ' C1 ', ' C2 ', ' P1 ', ' P2 ', ' object ']

As mentioned above, we get different results.

When instance D calls Foo (), the search order is d = C1 = C2 = P1

When instance D calls bar (), the search order is d = = C1 = C2

As you can see, the search method for the new class is to look for attributes in a "breadth-first" way.


We can use the __mro__ property to see the order of lookups.



Reference:

http://beginnersbook.com/2013/05/method-overloading/

Http://forums.udacity.com/questions/20750/method-overloading-in-python

Https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions

http://2577885.blog.51cto.com/2567885/669322

http://blog.csdn.net/seizef/article/details/5310107

Http://www.cnblogs.com/Joans/archive/2012/11/09/2757368.html


Python Interview-override & Overload

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.