简体   繁体   中英

Override property setter abstract method in child class

I've been exploring the @property decorator and abstract classes for the first time and followed along with the Python docs to define the following classes:

In [125]: from abc import ABC, abstractmethod
     ...: class C(ABC):
     ...:     def __init__(self):
     ...:         self._x = None
     ...:     @property
     ...:     def x(self):
     ...:         """I'm the 'x' property"""
     ...:         return self._x
     ...:     @x.setter
     ...:     @abstractmethod
     ...:     def x(self, value):
     ...:         self._x = value
     ...:     @x.deleter
     ...:     def x(self):
     ...:         del self._x
     ...: class D(C):
     ...:     pass

The setter property in class C is an abstractmethod . I'm aware that I must override this setter property(method) in class D in order to instantiate an object, but I'm unsure how to do that as all methods in class C are named the same. Now, I know, I could just call the methods getx() , setx() etc. in class C and just override setx() in class D, but I want to know if there's a way to do it with the property syntax above.

The docs show that its possible to override the setter property like this:

  ...: class D(C):
  ...:     @C.x.setter #override setter
  ...:     def x(self):
  ...:         pass

and now the child class D can be instantiated:

In [128]: d = D()
In [129]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM