Python class -- How may I access an double underscored attribute that is added through object within a method of the class

25 Views Asked by At

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.

1

There are 1 best solutions below

0
Frank Yellin On

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 __breadth from outside, you should have a set_breadth method inside the class.

class Rectangle:
    ...
    def set_breadth(value):
        self.__breadth = value

b.set_breadth(5)

Alternatively, create a breadth property. Google "Python Properties" to learn how to do this.