Private Variables
In Python, private variables are variables that are intended to be used only within the class in which they are defined, and not by external code. Private variables are not directly accessible from outside the class.
To define a private variable in the Circle
class, you can use the double underscore prefix (__
) followed by the variable name. For example:
class Circle:
def __init__(self, radius):
self.__radius = radius
This defines a private variable __radius
in the Circle
class.
Private variables are intended to be used only within the class in which they are defined. They are not directly accessible from outside the class. For example, if you try to access the __radius
variable from outside the Circle
class, you will get an error:
circle1 = Circle(5)
print(circle1.__radius) ## This will raise an AttributeError
Private variables are useful for encapsulating data within a class and limiting the ability of external code to modify it. However, it is important to note that private variables are not truly private in Python, and can still be accessed from outside the class using "name mangling".
Name mangling is a technique that involves adding a special prefix to the variable name to make it harder to access from outside the class.
For example, the __radius
variable can still be accessed from outside the Circle
class using the following syntax:
print(circle1._Circle__radius) ## This will print 5
However, this is not considered a good programming practice and should be avoided.
Instead, you should use private variables only within the class in which they are defined and provide public methods to access or modify the data if necessary.
Here's an example of a Circle class with a private __radius
variable and public methods to access and modify the radius:
class Circle:
def __init__(self, radius):
self.__radius = radius
def get_radius(self):
return self.__radius
def set_radius(self, radius):
self.__radius = radius
To access the radius of a Circle object, you can use the get_radius
method:
circle1 = Circle(5)
print(circle1.get_radius()) ## prints 5
To modify the radius of a Circle object, you can use the set_radius
method:
circle1.set_radius(10)
print(circle1.get_radius()) ## prints 10