May-02-2018, 08:18 PM
Hello guys,
I'm trying to inherit private attributes (self.__attrib), but when I use the parent __init__ method this private attributes doesn't inherit. For example:
1 - Use public attributes: self.param2 instead of self.__param2. It is not an important problem, but conceptually, the attributes that will not be accessed out of class, must be private. Not?
2- Not reutilize the Primary __init__ constructor. But we are wasting inheritance potencial, not? Like this:
Thanks a lot
I'm trying to inherit private attributes (self.__attrib), but when I use the parent __init__ method this private attributes doesn't inherit. For example:
class Primary():
def __init__(self, param1, param2):
self.param1 = param1
self.__param2 = param2
def getP1(self):
return self.param1
def getP2(self):
return self.__param2
class Secondary(Primary):
def __init__(self, param1, param2, param3):
Primary.__init__(self, param1, param2)
self.__param3 = param3
def getP3(self):
return self.__param3
def test(self):
print (self.__param2)
#Main
p = Primary('a', 'b')
s = Secondary('a', 'b', 'c')
s.test()When I try to access self.__param2 in Secondary instance, there is an error:Error:Traceback (most recent call last):
File "class_test.py", line 38, in <module>
s.test()
File "class_test.py", line 21, in test
print (self.__param2)
AttributeError: 'Secondary' object has no attribute '_Secondary__param2'I think in three solutions:1 - Use public attributes: self.param2 instead of self.__param2. It is not an important problem, but conceptually, the attributes that will not be accessed out of class, must be private. Not?
2- Not reutilize the Primary __init__ constructor. But we are wasting inheritance potencial, not? Like this:
class Secondary(Primary): def __init__(self, param1, param2, param3): self.param1 = param1 self.__param2 = param2 self.__param3 = param33- Use parent get() method when I need it (maybe the best solution):
def test(self): print (Primary.getP2(self))Any best solution? Maybe the best is the third option, not?
Thanks a lot
