[SOLVED] Python inheritance problems, return the different value – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by tttio

Now I have class like this:

id_A = 'A'
id_B = 'B'
id_C = 'C'

class A:
    def get_id(self):
        # The expected output: id_A

class B(A):
...
...

class C(A):
...
...

How to use inheritance to enable B and C to output id_ B,id_C?

like:

a = A()
b = B()
c = C()

a.get_id (Output should be 'A')
b.get_id (Output should be 'B')
c.get_id (Output should be 'C')

Thanks for any help



Solution

Just as guys suggested, you could override parent attribute in sub class like next:

test.py:

id_A = 'A'
id_B = 'B'
id_C = 'C'

class A:
    def __init__(self):
        self.identity = id_A

    def get_id(self):
        return self.identity

class B(A):
    def __init__(self):
        self.identity = id_B

class C(A):
    def __init__(self):
        self.identity = id_C

a = A()
b = B()
c = C()

print(a.get_id())
print(b.get_id())
print(c.get_id())

execution:

# python3 test.py
A
B
C

Update according new coments, you could also use classmethod without __init__(self):

id_A = 'A'
id_B = 'B'
id_C = 'C'

class A:
    identity = id_A

    @classmethod
    def get_id(cls):
        return cls.identity

class B(A):
    identity = id_B

class C(A):
    identity = id_C

a = A()
b = B()
c = C()

print(a.get_id())
print(b.get_id())
print(c.get_id())

Execution:

$ python3 test.py
A
B
C


This Question was asked in StackOverflow by tttio and Answered by atline It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?