I am just trying to practice coding an abstract method in Python and i have the following code for it:
import abc
class test(abc.ABC):
@abc.abstractmethod
def first(self,name):
"""This is to be implemented"""
class Extendtest(test):
def __init__(self,name):
self.name = name
def first(self):
print ("Changing name!")
self.name = "Shaayan"
def second(self,value):
print ("Adding second argument!")
self.value = value
e = Extendtest("Subhayan")
print (e.name)
e.first()
print (e.name)
I intentionally changed the signature of the first method in the implementation of the abstract method.
But if i change the signature Python is not giving any error and is going through as expected.
Is there no way in Python by which i can force strict abstraction ?
-
In Python abstract methods are not necessary. Just use duck-typing.Daniel– Daniel2017年05月27日 15:25:57 +00:00Commented May 27, 2017 at 15:25
1 Answer 1
This is not a new question asked about python and a short answer:
No, it is not possible. The easiest way is either to reuse a custom library like zope or implement this behavior by your own.
There was a proposal on ABC to check arguments and here is what Guido answers on this:
That is not a new idea. So far I have always rejected it because I worry about both false positives and false negatives. Trying to enforce that the method behaves as it should (or even its return type) is hopeless; there can be a variety of reasons to modify the argument list while still conforming to (the intent of) the interface. I also worry that it will slow everything down.
That said, if you want to provide a standard mechanism that can optionally be turned on to check argument conformance, e.g. by using a class or method decorator on the subclass, I would be fine with that (as long as it runs purely at class-definition time; it shouldn't slow down class instantiation or method calls). It will probably even find some bugs. It will also surely have to be tuned to avoid certain classes false positives.