More than 06 states

Polymorphism

Conditions of the polymorphic implementation: inheritance, override inherited methods

Objective polymorphism: an interface reuse. An interface passed in different objects, the method for performing the same, different results .

For example, the definition of a parent class: printer. Two sub-categories: color printers, monochrome printers.

Definition of a human, the method used with the printer, using a different printer, to print different results.

class Printer(object):
    def print_something(self):
        pass


class ColorPrinter(Printer):
    def print_something(self):
        print ( "print out color content")


class BlackPrinter(Printer):
    def print_something(self):
        print ( "Print out the contents of the black and white")


class Person(object):
    def make_print(self, obj):
        obj.print_something()


bp = BlackPrinter()
cp = ColorPrinter()
xiaoming = Person()
When xiaoming.make_print (cp) # incoming cp, the result is: print out the color content. When incoming bp, the result is: black and white print out the contents

  

 

Guess you like

Origin www.cnblogs.com/scopicat/p/11719753.html