2

Update

Actually, I have tested all the answers, but a feature I want still can't be achieved. Using @property force the subclass to directly declare the property but not something like self.property = xxx in one function. How could I also achieve this?

I mean, if the subclass __get__ the property before __set__, then raise NotImplementedError.


How to declare a variable in the super class which should be implemented in the subclass?

In other word, I want to declare a virtual variable in super class.

class A:

    def a(self):               # perfect!
        raise NotImplementedError("...") 

    b = raise NotImplementedError("...")      #how to declare a variable similar with the function above?
Sraw
  • 18,892
  • 11
  • 54
  • 87

2 Answers2

1

Since Python doesn't really have something called virtual objects, you can mimic in case of methods by explicitly raising exception but in the case of variables, you can either override __init__ or use properties instead of variables.

class A(object):

    def __init__(self, *args, **kwargs):
        if not hasattr(self, 'b'):
            raise NotImplementedError("...")

class B(A):
    b = 3
hspandher
  • 15,934
  • 2
  • 32
  • 45
0

You can use the property decorator. For more information, please check this thread where you can get a detailed answer.

Community
  • 1
  • 1
blasrodri
  • 448
  • 5
  • 16