Home > other >  Python inheritance problems, return the different value
Python inheritance problems, return the different value

Time:09-19

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
        return id_A

class B(A):
...
...
    def __init__(self):
        pass

class C(A):
...
...
    def __init__(self):
        pass

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

CodePudding user response:

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
  • Related