How do you create private attributes in a Python class?
Creating private attributes in Python classes
In Python, you can create private attributes in a class by prefixing the attribute name with double underscores __. This practice is often referred to as "name mangling," which makes the attribute name harder to access from outside the class. Though it isn't true encapsulation, it discourages direct access to these attributes and signals their private nature.
Note: "Private" instance variables that cannot be accessed except from inside an object don't exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.
Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
Here's how you create private attributes in a class:
Code:
class Student:
def __init__(self):
self.public_attr_name = 'Seachlann Sara'
self.__private_attr_id = 12
obj = Student()
print(obj.public_attr_name) # Accessing a public attribute
#print(obj.__private_attr_name) # This will raise an AttributeError
# However, you can still access the private attribute using name mangling
print(obj._Student__private_attr_id)
Output:
Seachlann Sara 12
In the example above , public_attr is a public attribute and can be accessed directly. On the other hand, __private_attr is a private attribute and should not be accessed directly. Attempting to access it directly will raise an AttributeError. You can, however, access it through the name-mangled version 'Student_private_attr', but this practice is discouraged since it violates encapsulation.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-interview/how-do-you-create-private-attributes-in-a-class.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics