I am trying to use an abstract base class using the abc.ABCMeta . Here is the sample code -
import abc
class A(metaclass=abc.ABCMeta):
def __init__(self):
self.v1 = 10
self.v2 = 10
@abc.abstractmethod
def first_method(self):
pass
class B(A):
def __init__(self):
self.v2= 20
def first_method(self):
pass
if __name__ == '__main__':
b = B()
print("v1 =%d", b.v1)
print("v2=%d", b.v2)
If I do not define __init__ in class B, it would just take the values of v1 and v2 from the superclass A. But,I want to use the value of v1 from the abstract class A and override the value of variable v2. If I try to call super.__init__(self) it gives an error. Can someone please let me know the way to accomplish this? Thank you.
UPDATE: Got the following error message with the above sample code:
AttributeError: 'B' object has no attribute 'v1'
2 Answers 2
You should use super().__init__() instead of super.__init__(self).
Comments
this should work.
import abc
class A(metaclass=abc.ABCMeta):
def __init__(self):
self.v1 = 10
self.v2 = 10
@abc.abstractmethod
def first_method(self):
pass
class B(A):
def __init__(self):
super(B, self).__init__()
self.v2 = 20
def first_method(self):
pass
if __name__ == '__main__':
b = B()
print('v1 = ', b.v1)
print('v2 = ', b.v2)
5 Comments
type(A) in Python 2 and 3; Python 3 doesn't look at the __metaclass__ attribute in the definition, so A isn't an abstract base class.
AttributeError: 'B' object has no attribute 'v1'super().__init__(self)included? It probably says__init__() takes 1 positional argument but 2 were given. Try without theselfparameter, its already included in thesuper()call.super().__init__()please post the answer so that i can accept :-)