Ir al contenido principal

Clases abstractas con python

¿Como se crean clases abstractas con python?.

Voy a explicar cual es la forma correcta de definir una clase abstracta y heredar de ella. El procedimiento general es:
  1. Definir una clase abstracta utilizando una metaclase.
  2. Definir la subclase de la clase abstracta (sin herencia).
  3. Registrar esta última clase como subclase de la clase abstracta.

Tomemos como ejemplo el siguiente código:

from abc import ABCMeta, abstractmethod

class AbstractFoo:
    __metaclass__ = ABCMeta
    
    @abstractmethod
    def bar(self):
        pass

    @classmethod
    def __subclasshook__(cls, C):
        return NotImplemented



class Foo(object):
    def bar(self):
        print "hola"


AbstractFoo.register(Foo) 

Lo primero que hacemos es importar del módulo abc la clase ABCMeta y el decorador abstractmethod.

La clase ABCMeta es la metaclase que utilizamos para definir las clases abstractas, nos aporta una serie de funcionalidades.

Una vez hemos asignada la metaclase, definimos un método abstracto que deberá ser implementado por las subclases, el método bar.

De momento nos olvidamos del método __subclasshook__.

Posteriormente definimos la clase que concretará a la clase abstracta implementando el método abstracto.

Para terminar se registra como subclase de la clase abstracta con el método register. Con esto hacemos que la sentencia issubclass(some_var, AbstracFoo) devuelva True.

Como hemos visto, para que se considere subclase de la clase abstracta la clase concreta debe registrarse como subclase. Pero, ¿que pasa si queremos que cualquier otra clase sea considerada subclase de la abstracta y no la hemos registrado como subclase?

Para este problema tenemos el método __subclasshook__, que personalizará el comportamiento de issubclass sin necesidad de tener que invocar a register previamente. Este método debe devolver True, False o NotImplemented.

Comentarios

  1. Muy buena entrada Jesús, práctica y concisa.
    Te cuento que también llevo a delante un blog y hace un tiempo también escribí sobre clases en python.
    Seguire tus avances!!!
    Saludos, Diego

    ResponderEliminar
    Respuestas
    1. Muy buenas, aunque algo leo algo tarde el comentario añado tu blog a marcadores.

      Un saludo!!

      Eliminar

Publicar un comentario

Entradas populares de este blog

Stop measuring time with time.clock() in Python3

If we read the time.clock() documentation ( https://docs.python.org/3/library/time.html#time.clock): Deprecated since version 3.3: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour. I use time.perf_counter, but feel free to use time.process_time if fits for your requirements. The main difference they have are: time.perf_counter() It does include time elapsed during sleep and is system-wide. time.process_time() It does not include time elapsed during sleep. It is process-wide by definition.

Polynomial regression using python

We are going to learn how to create a polynomial regression and make a prediction over a future value using python. The data set have been fetched from INE (national statistics institute) , that data is the EPA ( active population survey ), that tell us the national total (Spain), both genders. 16 and over are unemployed ( in thousands ). Example data: label serie rate 0 2002T1 0 2152.8 1 2002T2 1 2103.3 2 2002T3 2 2196.0 3 2002T4 3 2232.4 4 2003T1 4 2328.5 Data CSV can be downloaded here: https://drive.google.com/file/d/1fwvAZe7lah5DX8-DDEpmfeUDYQhKcfzG/view?usp=sharing Lets see how looks that data: Fine, as we can see the data describe a curve, so its for that because we want to use a polynomial regression. To try to approximate that curve we will use a grade 2 polynomial or...

Use django ORM standalone within your nameko micro-services

Learning about micro services with python, I found a great tool named nameko . https://www.nameko.io/ Nameko is a Python framework to build microservices that doesn't care in concrete technologies you will use within your project. To allow that microservices to work with a database, you can install into your project a wide variety of third parties, like SQLAlchemy (just like any other). To have an easy way to communicate with the database and keep track of the changes made to the models, I chose Django: I'm just learning about microservices and I want to keep focused on that. Easy to use, Django is a reliable web framework, have a powerful and well known ORM. Also using Django we will have many of the different functionalities that this framework provide. To make all this magic to work together, I developed a python package that allow you to use Django as a Nameko injected dependency: https://pypi.org/project/django-nameko-standalone/ You can found the source ...