In the below program is it possible to access __breadth attribute in area(self) method?
class Rectangle:
def __init__(self, L):
self.__length = L
def area(self):
return self.__length * self.__breadth
b = Rectangle(10)
b.__breadth = 5
print(b.__dict__)
print(b.area())
I have tried to access __braedth in the area(self) method but it is not possible.
You should never have written
b.__breadth = 5. The intent of double underscore is that this variable is private to the class and should never be accessed from outside it. If you need to modify__breadthfrom outside, you should have aset_breadthmethod inside the class.Alternatively, create a
breadthproperty. Google "Python Properties" to learn how to do this.