What is the meaning of single and double underscore before an object name in Python?
In Python, single underscore _
before an object name means that the object is meant to be private, and shouldn't be directly accessed from outside the class. However, it is just a naming convention, and there is nothing actually stopping you from accessing these objects.
On the other hand, double underscore __
before an object name is used to create so-called "name mangling". This is a way to make instance variables less likely to collide with variables in subclasses. When a class attribute name is preceded by two underscores, Python replaces each underscore and the character following it with the name of the class, in order to avoid name clashes between attributes in different classes. For example:
class MyClass:
def __init__(self):
self.__private = 42
obj = MyClass()
print(obj.__private) # this will raise an AttributeError
print(obj._MyClass__private) # this works
Name mangling is not intended to provide real privacy; it is just a way to avoid accidental name clashes between class attributes. If you really want to prevent external access to an object, you should use the private
module, which provides a more robust way of creating private variables in Python.
-
Difference between static and class methods in Python?
Class method To create a class method, use the @classmethod decorator. Class methods receive the class as an implicit first argument, just like an instance method receives the instance. The class m...
Questions -
How to check if an object has an attribute in Python?
To check if an object has an attribute in Python, you can use the hasattr function. This function takes two arguments: the object and the attribute name as a string. It returns True if the object h...
Questions -
How to determine the type of an object in Python?
You can use the type() function to determine the type of an object in Python. For example: x = 10 print(type(x)) # Output: <class 'int'> y = "hello" print(type(y)) # Output: <class 'str'> z = [1,...
Questions -
Getting the class name of an instance in Python?
You can use the built-in type() function to get the class name of an instance in Python. For example: class MyClass: pass myinstance = MyClass() print(type(myinstance).name) This will output My...
Questions
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github