Ask Your Question
2

What are the methods to prevent the instantiation of a Python class without any abstract methods?

asked 2023-07-05 05:25:34 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-05 05:39:01 +0000

huitzilopochtli gravatar image
  1. Define at least one abstract method in the class. This will force any subclass to implement the abstract method before it can be instantiated.

  2. Make the class itself abstract by adding the abstract keyword before the class definition. This will prevent the class from being instantiated directly, but will still allow subclassing and instantiation of the subclass.

  3. Implement a private constructor method for the class and raise an exception if it is called. This will prevent the class from being instantiated directly and force a subclass to implement its own constructor.

Example:

from abc import ABC, abstractmethod

class MyClass(ABC):

  # Define at least one abstract method
  @abstractmethod
  def my_method(self):
    pass

  # Make the class abstract
  @classmethod
  def __subclasshook__(cls, C):
    if cls is MyClass:
      if any("my_method" in B.__dict__ for B in C.__mro__):
        return True
    return NotImplemented

  # Implement a private constructor method
  def __init__(self):
    raise Exception("MyClass cannot be instantiated directly")

class MySubClass(MyClass):

  # Implement the abstract method
  def my_method(self):
    print("MySubClass method called")

# This will raise an exception
my_class = MyClass()

# This will work
my_subclass = MySubClass()
my_subclass.my_method()
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-05 05:25:34 +0000

Seen: 9 times

Last updated: Jul 05 '23