codehaus


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Question on ABC classes


I'm a C++ programmer and Python programmer as well.  Python classes are not exactly like C++ classes.

If you define a class where every method has an implementation, then it really isn't abstract.  It can be instantiated.  You can force it to be abstract by doing from abc import ABCMeta and declare class myclass(metaClass=ABCMeta).  Otherwise, Python does not have a way to know that you intend the class to be abstract unless it contains an @abstractmethod that makes it actually abstract.   Such a method must be overridden.

Usually, an Abstract Base Class defines an interface.  You can make all the functions @abstractmethod, and separately make a another class that is based on your ABC and provides default implementations for all the functions.  Other classes can be based on that class.   I am not an authority on this so let me refer you to actual documentation:

See: https://docs.python.org/3/library/abc.html, that should help you. 

-----Original Message-----
From: Julio Di Egidio <julio at diegidio.name> 
Sent: Thursday, October 22, 2020 12:26 PM
To: python-list at python.org
Subject: Question on ABC classes

Hello guys,

I am professional programmer but quite new to Python, and I am trying to get the grips of some peculiarities of the language.

Here is a basic question: if I define an ABC class, I can still instantiate the class unless there are abstract methods defined in the class.

(In the typical OO language the class would be not instantiable, period, since it's "abstract".  But this is not so in Python, to the point that, also for uniformity, I am feeling compelled to define an @abstractmethod __init__ in my ABC classes, whether they need one or not, and whether there are other abstract methods in the class or not.)

Now, I do read in the docs that that is as intended, but I am not understanding the rationale of it: why only if there are abstract methods defined in an ABC class is instantiation disallowed?  IOW, why isn't subclassing from ABC enough?

Thanks for any enlightenment,

Julio