In Python 2.x when you want to mark a method as abstract, you can define it like so:
JavaScript
x
4
1
class Base:
2
def foo(self):
3
raise NotImplementedError("Subclasses should implement this!")
4
Then if you forget to override it, you get a nice reminder exception. Is there an equivalent way to mark a field as abstract? Or is stating it in the class docstring all you can do?
At first I thought I could set the field to NotImplemented, but when I looked up what it’s actually for (rich comparisons) it seemed abusive.
Advertisement
Answer
Yes, you can. Use the @property
decorator. For instance, if you have a field called “example” then can’t you do something like this:
JavaScript
1
6
1
class Base(object):
2
3
@property
4
def example(self):
5
raise NotImplementedError("Subclasses should implement this!")
6
Running the following produces a NotImplementedError
just like you want.
JavaScript
1
3
1
b = Base()
2
print b.example
3