Python inheritance problems, return the different value
Question:
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
Answers:
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
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
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