Introduction:
Just like you, a newbie in python scripting language, me too was confused about lot of new things in python that are not valid or available in other languages like Java, .Net etc.
Just like other things i had seen the use of '_' underscore in python, at beginning level that flabbergasted me for a while.
With some research and practice i have summarised the following usage of '_' underscore in python. Hope you will find it helpful at beginning level.
1 2 3 4 5 6 7 | _ = input() # For example you typed '5' print(_) # This will print '5' print( int( _ ) * int( _ ) ) # This will print '25' print( int( _ ) + 10 ) |
The above will print '15', because last input was "5" and in above line of code is producing '25' as output but not being handled by ' _ ' .
I had to convert _ to Integer with int(_) because input() method from python version 3.X takes everything as string.
Second Usage: Single leading '_' is to declare the variables, function, methods and classes in module as private.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | _privateVariable="" # private variable with single leading underscore. class _privateClass: _itsPrivateVariable="PrivateValue" def _privateMethod(self): # print (_itsPrivateVari); # the above line will produce error as it is accessing # private var. print (_privateClass._privateVariable) print (self._itsPrivateVariable) # above two lines are two different methods to access the private var # CLASSNAME.PRIVATEVAR ... # or # use the 'self' keyword OBJ=_privateClass() OBJ._privateMethod() |
Third Usage: Single trailing '_' to avoid conflicts with python's inbuilt keywords.
1 2 3 4 5 6 7 | class new: def class_(self): print("hello from class_") _list_=["private","LIST","With","Trailing","Underscore","to avoid","ambiguity"] '''Private list variable with leading underscore declares it private and trailing underscore resolves the conflict with reserved keyword 'list'.''' |
Fourth Usage: For mangling the method names, just like in java overriding concept.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class A: def _parrot(self): print(" _parrot says HELLO!! ") def __dog(self): print(" __dog() of class A.") class B(A): # class B is inheriting class A def __dog(self): print(" __dog() of class B.") OBJ_A=A() # creating objects OBJ_B=B() # creating objects OBJ_A._parrot() OBJ_A._A__dog() OBJ_B._B__dog() OBJ_B._A__dog() |
Problem is class B is child class A, means that class B will have access to class A's methods and variables i.e
method _parrot() and __dog() .
The real mess is that how we, other developers or python will know with what object, which method to call?
OBJ_A._parrot() clearly defines that OBJ_A is object of class A and calling it's private method _parrot(), no doubt about it.
OBJ_A._A__dog(), OBJ_A is object of class A and calling it's mangled method __dog(), how can we be sure about it?
Pay little attention here, normally we call any method with objName.methodName(), here in this case we are calling __dog() method with concatenating _ClassName in front of __dog() method.
In OBJ_A._A__dog() the '_A' after dot(.) and before __dog() defines that this __dog() belongs to class A.
Hope the next two lines will provide a lucid vision of mangling.
OBJ_B._B__dog() is calling __dog() method of class B.
OBJ_B._A__dog() is calling __dog() method of class A.
In java this processing is called "overriding" in python we can say is "Mangling"
Output:-
_parrot says HELLO!!
__dog() of class A.
__dog() of class B.
__dog() of class A.
Fifth Usage: To create special methods.
This convention is used to create special variables or methods (so-called “magic method”) such as __init__, __len__.
These methods provides special syntactic features or does special things.
For example, __init__ works a constructor in a class.
A user of course can make custom special method, it is very rare case, but often might modify the some built-in special methods.
But most experienced python developer recommend to avoid this convention to create your own special "magic methods".
Sixth Usage: To Ignoring values.
# Ignore a value when unpacking
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # Ignore a value when unpacking x, _ , y = (1, 2, 3) # x = 1, y = 3 # Ignore the multiple values. It is called "Extended Unpacking" which is available in only Python 3.x x, *_ , y = (1, 2, 3, 4, 5) # x = 1, y = 5 # Ignore the index for _ in range(10): do_something() # Ignore a value of specific location for _, val in list_of_tuple: do_something() |
Your comments are valuable for this blog. And every one is invited to make valid corrections and make this blog helpful others.
Please do share your experiences and problems regarding this blog and its content, surly i will help you.
Thanks in anticipation.
Pran.
Thank you so much for making this blog. I was searching for some beginner level python tutorial to clear my confusions and this is the one. It really helped a lot. Thank you so much Pran Sukh (Blogger) for your efforts.
ReplyDeleteThanks. M also a bigener in python... I'm not helping anybody, on the contrary we are helping each other.
DeleteHi thanks for the blog.
ReplyDeleteBeing a beginner i am always in search for some helpful blogs.
It really worked for me.
Thanks Pran Sukh....
very nice bro
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteGreat post
ReplyDeleteA little note:
"Single leading '_' is to declare the variables, function, methods and classes in module as private."
This is by convention, and is not enforced by the interpreter.