cppb
cppb

Reputation: 2419

python3 use of abstract base class for inheriting attributes

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'

Upvotes: 0

Views: 188

Answers (2)

Ziyad Mestour
Ziyad Mestour

Reputation: 97

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)

Upvotes: 0

Yaroslav Admin
Yaroslav Admin

Reputation: 14535

You should use super().__init__() instead of super.__init__(self).

Upvotes: 4

Related Questions