the ability to create abstract variables so you can encourage the user to override a class variable so you can encourage a user to override it
Use ABC.
from abc import ABC, abstractmethod
class BaseClass(ABC):
# Abstract method (must be overridden in subclass)
@abstractmethod
def do_something(self):
pass
class SubClass(BaseClass):
# Implementing the abstract method
def do_something(self):
print("Doing something!")
# Usage
sub = SubClass()
sub.do_something() # Doing something!
Moving to the Help category as this is not framed as a clear, detailed proposal and may already be solved by the abc
module.
More to the point you can define abstract properties:
from abc import ABC, abstractmethod
class BaseClass(ABC):
# Abstract property (must be defined in subclass)
@property
@abstractmethod
def required_property(self):
pass
@classmethod
def provided_method(cls):
print(cls.required_property)
class SubClass(BaseClass):
# Implementing the abstract property
required_property = "I am from subclass"
# Usage
SubClass.provided_method() # I am from subclass
class BadSubClass(BaseClass):
pass
BadSubClass() # TypeError: Can't instantiate abstract class
This replaces the property with a str
value. abc
is satisfied, because it doesn’t care what gets bound to the name required_property
, as long as something does.
Ah, I see you are correct.
I was being lazy with syntax at the expense of semantics.
You can implement the abstract property more precisely like this:
class SubClass(BaseClass):
# Implementing the abstract property
@property
def required_property(cls):
return "I am from subclass"
being a property you can still access it succinctly:
SubClass().required_property
However, since they want a class variable, and class properties are (I’ve just discovered) deprecated, it might be best to override the property and make a class attribute anyway.
Unless ABC provides a way to make an abstract attribute I can’t think of a better way.