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

Question on ABC classes

On Thursday, 22 October 2020 23:04:25 UTC+2, Ethan Furman  wrote:
> On 10/22/20 9:25 AM, Julio Di Egidio wrote:
> > 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?
> Let's say you subclass from ABC:
>    class Abstract(ABC):
>        pass
> Then you subclass from that:
>    class Concrete(Abstract):
>        pass
> Then subclass from that:
>    class MoreConcrete(Concrete):
>        pass
> If you do a
>    issubclass(<any of the above classes>, ABC)
> you'll get
>    True

Ah, right, that's the point I was missing: how to tell the
compiler when a more derived class is *not* abstract...

I was indeed making the mistake of inheriting from ABC also
in the derived classes, and omitting it in the classes that
are eventually concrete, not realising that ABC isn't just
a keywork or a decorator, so it gets inherited all the way.

> The idea behind abstract classes is the prevention of creating
> non-functional instances

Well, in Python, not in any other OO language, where abstract
is just synonym with must-override (hence cannot instantiate),
no other constraints.

I am now thinking whether I could achieve the "standard"
behaviour via another approach, say with decorators, somehow
intercepting calls to __new__... maybe.  Anyway, abstract
classes are the gist of most library code, and I remain a bit
puzzled by the behaviour implemented in Python: but I am not
complaining, I know it will take me some time before I actually
understand the language...

For now, thank you and Marco very much for your feedback,