Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mark a class abstract even if all its methods are implemented?

Is there a way to mark a python class as abstract or un-instantiable even if all its abstract methods have been implemented?

class Component(ABC):
    @abstractmethod
    def operation(self) -> None:
        pass

class Decorator(Component): # I would like this class to be abstract
    def operation(self) -> None:
        print("basic operation")

The only workaround I found is to choose some method in the class to have both implementation and @abstractmethod decorator, but then python requires derivers of the child abstract class to re-implement the method.

This too can be worked around by having the child class calling super() , but pylint complains that this is a useless call.

class Component(ABC):
    @abstractmethod
    def operation(self) -> None:
        pass

class Decorator(Component): # I would like this class to be abstract
    @abstractmethod
    def operation(self) -> None:
        print("basic operation")

class ConcreteDecorator(Decorator): 
    def operation(self) -> None: # python makes child class re-implement
        super().operation()  # pylint complains about useless super delegation

Is there a better way to do this?
I tried using a method with implementation and @abstractmethod decorator, but then deriving classes need to reimplement. I'm looking for a solution at "compile time", not a run time error.

like image 500
Gonen I Avatar asked Oct 19 '21 16:10

Gonen I


People also ask

Can a class can be abstract even if all of its methods are concrete?

No. Abstract class can have both an abstract as well as concrete methods. A concrete class can only have concrete methods. Even a single abstract method makes the class abstract.

Can abstract class have methods with implementation?

Core Java Tutorial An abstract class can have an abstract method without body and it can have methods with implementation also. abstract keyword is used to create a abstract class and method. Abstract class in java can't be instantiated.

Is it allowed to mark a method abstract method without marking the class abstract?

And yes, you can declare abstract class without defining an abstract method in it.

Is it valid to define an abstract class that only contains fully implemented ie not abstract methods if so will Java let you create instances of this type?

You can make a class as abstract ,even if you don't want to implement all of the interface methods that the class implements. According to java docs. It was noted that a class that implements an interface must implement all of the interface's methods.

Is it necessary to implement all the abstract methods when extending abstract?

Yes, when you extends abstract you should give implementation for all abstract methods which are presents in abstract class. Othrewise you should make it implementation class as abtract class. You must implement all the abstract methods you have in the abstract class.

How to declare an abstract method in Java?

To declare an abstract method, use this general form: As you can see, no method body is present. Any concrete class (i.e. class without abstract keyword) that extends an abstract class must override all the abstract methods of the class. Consider the following Java program, that illustrate the use of abstract keyword with classes and methods.

How do you implement features of an abstract class?

To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass. A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.

Is it mandatory to override abstract methods of a subclass?

However, if the subclass is declared abstract, it's not mandatory to override abstract methods. We can access the static attributes and methods of an abstract class using the reference of the abstract class. For example, Did you find this article helpful?


Video Answer


1 Answers

Create a helper class that overrides the __new__ function to check whether cls.__bases__ contains itself.

class UnInstantiable:
    def __new__(cls, *args, **kwargs):
        if __class__ in cls.__bases__:
            raise TypeError(f"Can't instantiate un-instantiable class {cls.__name__}")

        return super().__new__(cls)

Usage:

# class Decorator(Component):                # Add UnInstantiable base class
class Decorator(Component, UnInstantiable):  # like this
    def operation(self) -> None:
        print("basic operation")


Decorator()  # TypeError: Can't instantiate un-instantiable class Decorator
like image 95
aaron Avatar answered Oct 23 '22 00:10

aaron