Why do we use _ in variable names?
I have seen variables like _ image and was wondering what _ meant?
Solution 1:
It doesn't mean anything. It is rather a common naming convention for private member variables to keep them separated from methods and public properties. For example:
class Foo
{
private int _counter;
public int GetCounter()
{
return _counter;
}
public int SetCounter(int counter)
{
_counter = counter;
}
}
Solution 2:
In most languages _
is the only character allowed in variable names besides letters and numbers. Here are some common use cases:
- Separating words:
some_variable
- Private variables start with underscores:
_private
- Adding at the end to distinguish from a built-in name:
filter_
(sincefilter
is a built-in function) - By itself as an unused variable during looping:
[0 for _ in range(n)]
Note that some people really don't like that last use case.