How to make an attribute a private python
Learn how to make an attribute private in Python with a practical example.
Making an Attribute Private in Python
In Python, private attributes are attributes that are not accessible from outside the class definition. They are like variables in a class, but they cannot be accessed directly from outside the class. To make a private attribute in Python, you need to prefix the attribute name with two underscores (__).
To illustrate, let's say you have a class called MyClass
. This class has an attribute called number
. To make this attribute private, you would write it like this:
class MyClass:
def __init__(self):
self.__number = 0
Notice that the attribute name number
is prefixed with two underscores. This makes it a private attribute. It cannot be accessed directly from outside the class definition.
You can still access the attribute from within the class definition. To do this, you can use the self.
keyword. For example, you can print the value of the private attribute like this:
class MyClass:
def __init__(self):
self.__number = 0
def print_number(self):
print(self.__number)
In the example, we define a method called print_number
that prints the value of the __number
attribute. Since the attribute is private, you cannot access it directly from outside the class definition. However, it can still be accessed from within the class definition, using the self.
keyword.
Therefore, to make an attribute private in Python, you need to prefix the attribute name with two underscores. This makes it inaccessible from outside the class definition, but it can still be accessed from within the class definition using the self.
keyword.