Ingwar :
I have some class Foo
and Bar
, that inherits of Foo
. And I need to raise error, when that not overriding all methods in parent class. Also do not let create new methods in Bar
. For example:
class Foo:
def __new__(self):
**Some forbidding magic**
def a(self):
pass
def b(self):
pass
class Bar(Foo):
def a(self):
pass
class Baz(Foo):
def a(self):
pass
def b(self):
pass
def c(self):
pass
>>> a = Bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SyntaxError: not all methods was overrided in Bar
>>> b = Baz()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SyntaxError: new methods found in Baz
How would be able to perform this?
avayert :
You can use the abc
module to achieve the first part:
>>> import abc
>>>
>>> class Base(abc.ABC):
... @abc.abstractmethod
... def a(self): ...
... @abc.abstractmethod
... def b(self): ...
...
>>> class ImproperChild(Base):
... def a(self): ...
...
>>> class ProperChild(Base):
... def a(self): ...
... def b(self): ...
...
>>> ImproperChild()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class ImproperChild with abstract methods b
>>> ProperChild()
<__main__.ProperChild object at 0x00000225EEA46070>
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=361331&siteId=1