I have a parent and child class. Parent class has 2 attributes x,y. Y can be set to private variable with __(double underscore) but I can’t expose it to the child class, so I have given it as a _(single underscore) exposing it to the child class.
But I don’t want it to be exposed other than the child class..
Is there anyway to override the init class in the child method to protect the y variable being exposed?
test.py
class parent:
def __init__(self,x):
self.x = x
self._y = ' '
self.setyvalue()
def setyvalue(self):
self._y = 10
return self._y
class child(parent):
def test(self):
print('self.x',self.x)
print('self._y',self._y)
if __name__ == '__main__':
x = child(2)
x.test()
By convention, a variable beginning with an underscore is considered as “private”, and it shouldn’t be used outside the class. Python doesn’t prevent it, but it’s the convention that should be respected. This is the way you do in Python: everything is allowed, but you document how it should be used.