I have two classes A and B which inherit from a Parent class. As stated in Access Child class variables in Parent class, its not good practice to reference child class attributes from parent classes. My question is if this also holds for object attributes defined in the child class (e.g. in the __init__
method of A and B). As an example, is it ok to do the following:
class Parent():
def print_c(self):
print(self.c)
class A(Parent):
def __init__(self):
super().__init__()
self.c = 4
class B(Parent):
def __init__(self):
super().__init__()
self.c = 7
a_obj = A()
a_obj.print_c() # prints 4
b_obj = B()
b_obj.print_c() # prints 7
Or is this the only "correct" way to do it:
class Parent():
def __init__(self, c):
self.c = c
def print_c(self):
print(self.c)
class A(Parent):
def __init__(self):
super().__init__(c=4)
class B(Parent):
def __init__(self):
super().__init__(c=7)
a_obj = A()
a_obj.print_c() # prints 4
b_obj = B()
b_obj.print_c() # prints 7
EDIT: As suggested by @MihailFeraru
from abc import ABC, abstractmethod
class Parent(ABC):
@abstractmethod
def get_c(self):
raise NotImplementedError
def print_c(self):
print(self.get_c())
class A(Parent):
def __init__(self):
super().__init__()
self.c = 4
def get_c(self):
return self.c
class B(Parent):
def __init__(self):
super().__init__()
self.c = 7
def get_c(self):
return self.c
a_obj = A()
a_obj.print_c() # prints 4
b_obj = B()
b_obj.print_c() # prints 7