Buscar..


Polimorfismo basico

El polimorfismo es la capacidad de realizar una acción en un objeto independientemente de su tipo. Esto generalmente se implementa creando una clase base y teniendo dos o más subclases que implementan todos los métodos con la misma firma. Cualquier otra función o método que manipule estos objetos puede llamar a los mismos métodos independientemente del tipo de objeto en el que esté operando, sin necesidad de realizar una verificación de tipo primero. En la terminología orientada a objetos, cuando la clase X extiende la clase Y, entonces Y se llama súper clase o clase base y X se llama subclase o clase derivada.

class Shape:
    """
    This is a parent class that is intended to be inherited by other classes
    """

    def calculate_area(self):
        """
        This method is intended to be overridden in subclasses.
        If a subclass doesn't implement it but it is called, NotImplemented will be raised.

        """
        raise NotImplemented

class Square(Shape):
    """
    This is a subclass of the Shape class, and represents a square
    """
    side_length = 2     # in this example, the sides are 2 units long

    def calculate_area(self):
        """
        This method overrides Shape.calculate_area(). When an object of type
        Square has its calculate_area() method called, this is the method that
        will be called, rather than the parent class' version.

        It performs the calculation necessary for this shape, a square, and
        returns the result.
        """
        return self.side_length * 2

class Triangle(Shape):
    """
    This is also a subclass of the Shape class, and it represents a triangle
    """
    base_length = 4
    height = 3

    def calculate_area(self):
        """
        This method also overrides Shape.calculate_area() and performs the area
        calculation for a triangle, returning the result.
        """

        return 0.5 * self.base_length * self.height

def get_area(input_obj):
    """
    This function accepts an input object, and will call that object's
    calculate_area() method. Note that the object type is not specified. It
    could be a Square, Triangle, or Shape object.
    """

    print(input_obj.calculate_area())

# Create one object of each class
shape_obj = Shape()
square_obj = Square()
triangle_obj = Triangle()

# Now pass each object, one at a time, to the get_area() function and see the
# result.
get_area(shape_obj)
get_area(square_obj)
get_area(triangle_obj)

Deberíamos ver esta salida:

Ninguna
4
6.0

¿Qué pasa sin el polimorfismo?
Sin polimorfismo, puede requerirse una verificación de tipo antes de realizar una acción en un objeto para determinar el método correcto para llamar. El siguiente ejemplo de contador realiza la misma tarea que el código anterior, pero sin el uso de polimorfismo, la función get_area() tiene que hacer más trabajo.

class Square:

    side_length = 2

    def calculate_square_area(self):
        return self.side_length ** 2

class Triangle:

    base_length = 4
    height = 3

    def calculate_triangle_area(self):
        return (0.5 * self.base_length) * self.height

def get_area(input_obj):

    # Notice the type checks that are now necessary here. These type checks
    # could get very complicated for a more complex example, resulting in
    # duplicate and difficult to maintain code.

    if type(input_obj).__name__ == "Square":
        area = input_obj.calculate_square_area()

    elif type(input_obj).__name__ == "Triangle":
        area = input_obj.calculate_triangle_area()

    print(area)

# Create one object of each class
square_obj = Square()
triangle_obj = Triangle()

# Now pass each object, one at a time, to the get_area() function and see the
# result.
get_area(square_obj)
get_area(triangle_obj)

Deberíamos ver esta salida:

4
6.0

Nota IMPORTANTE
Tenga en cuenta que las clases utilizadas en el ejemplo de contador son clases de "nuevo estilo" y se heredan implícitamente de la clase de objeto si se está utilizando Python 3. El polimorfismo funcionará tanto en Python 2.xy 3.x, pero el código de contraejemplo del polimorfismo generará una excepción si se ejecuta en un intérprete de Python 2.x porque escribe (input_obj). el nombre devolverá "instancia" en lugar del nombre de la clase si no se heredan explícitamente del objeto, lo que da como resultado que nunca se asigne un área.

Escribiendo pato

Polimorfismo sin herencia en forma de escritura de pato disponible en Python debido a su sistema de escritura dinámico. Esto significa que siempre que las clases contengan los mismos métodos, el intérprete de Python no distingue entre ellos, ya que la única comprobación de las llamadas se realiza en tiempo de ejecución.

class Duck:
    def quack(self):
        print("Quaaaaaack!")
    def feathers(self):
        print("The duck has white and gray feathers.")

class Person:
    def quack(self):
        print("The person imitates a duck.")
    def feathers(self):
        print("The person takes a feather from the ground and shows it.")
    def name(self):
        print("John Smith")

def in_the_forest(obj):
    obj.quack()
    obj.feathers()

donald = Duck()
john = Person()
in_the_forest(donald)
in_the_forest(john)

La salida es:

Quaaaaaack!
El pato tiene plumas blancas y grises.
La persona imita a un pato.
La persona toma una pluma del suelo y la muestra.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow