Quantcast
Channel: `staticmethod` and `abc.abstractmethod`: Will it blend? - Stack Overflow
Viewing all articles
Browse latest Browse all 6

Answer by Super Kai - Kazuya Ito for `staticmethod` and `abc.abstractmethod`: Will it blend?

$
0
0

The documentation says below:

When abstractmethod() is applied in combination with other methoddescriptors, it should be applied as the innermost decorator, ...

So, @abstractmethod must be the innermost decorator as shown below:

from abc import ABC, abstractmethodclass Person(ABC):    @classmethod    @abstractmethod # The innermost decorator    def test1(cls):        pass    @staticmethod    @abstractmethod # The innermost decorator    def test2():        pass    @property    @abstractmethod # The innermost decorator    def name(self):        pass    @name.setter    @abstractmethod # The innermost decorator    def name(self, name):        pass    @name.deleter    @abstractmethod # The innermost decorator    def name(self):        pass

Then, you need to override them in the child class as shown below:

class Student(Person):    def __init__(self, name):        self._name = name    @classmethod    def test1(cls): # Overrides abstract class method        print("Test1")    @staticmethod    def test2(): # Overrides abstract static method        print("Test2")    @property    def name(self): # Overrides abstract getter        return self._name    @name.setter    def name(self, name): # Overrides abstract setter        self._name = name    @name.deleter    def name(self): # Overrides abstract deleter        del self._name

Then, you can instantiate the child class and call them as shown below:

obj = Student("John") # Instantiates "Student" classobj.test1() # Class methodobj.test2() # Static methodprint(obj.name) # Getterobj.name = "Tom" # Setterprint(obj.name) # Getterdel obj.name # Deleterprint(hasattr(obj, "name"))

Output:

Test1Test2John Tom  False

You can see my answer which explains about abstract property.


Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>