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.
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
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
We are hiring.
Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.
Help us in making the internet more reliable.
Help us with developer education and get paid.