I am trying to have a child class inherit a method from some parent class that points to parent's own private variable. I want the inherited method of the child to use the child's own private variable. Is this possible, without redefining the whole method in the child class?
The code works fine if using public or protected (single underscore) variables. But our instructor insists on using private (double underscore) variables. We are only a couple of days into object-oriented programming so I do not really know what is the term I am looking for (sorry for that!).
I suspect I should only be using protected ones, but I want to comply with the instructions as much as possible.
class ClassA:
def __init__(self): self.__var = 10
def method1(self):
self.__var += 1 #method1 is intended to work on ClassA's __var
return self.__var #The method will also return the processed value of ClassA's __var
class ClassB(ClassA):
def __init__(self): self.__var = 20
#ClassA's method1 is inherited by ClassB.
#But I want this method1 to use ClassB's __var
ObjectA = ClassA()
ObjectB = ClassB()
print(ObjectA.method1()) #Will output 11
print(ObjectB.method1()) #Will raise an AttributeError, still looks for __var of ClassA
Above is just a demonstration of what I intend to achieve.
When using public or protected variables, I will have an output of 11
and 21
.
When using private variables however, I will have an 11
and an error.
I want ClassB
's method1
to use ClassB
's __var
(_ClassB__var
).
I could get ClassB
to have a variable named _ClassA__var
and set it to 20
, and it does work, but that is kind of messy IMO.
Edit: I think I've found an answer.
class ClassA:
def __init__(self): self.__var = 10
def method1(self): return self.get_var() + 1
def get_var(self): return self.__var
def set_var(self, val): self.__var = val
class ClassB(ClassA):
def __init__(self): self.__var = 20
def get_var(self): return self.__var
def set_var(self, val): self.__var = val
ObjectA = ClassA()
ObjectB = ClassB()
print(ObjectA.method1())
print(ObjectB.method1())
Instead of referencing the class attributes directly, I had the method point to a getter. This idea came from a comment under this post. As of this editing, it is not included in an answer, so I'm putting this here for clarity.
Thanks, @Allan!