Asked  6 Months ago    Answers:  5   Viewed   57 times

Coming from a C# background the naming convention for variables and method names are usually either camelCase or PascalCase:

// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()

In Python, I have seen the above but I have also seen underscores being used:

# python example
this_is_my_variable = 'a'
def this_is_my_function():

Is there a more preferable, definitive coding style for Python?

 Answers

97

See Python PEP 8: Function and Variable Names:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

Tuesday, June 1, 2021
 
motanelu
answered 6 Months ago
95

The underscore is simply a convention; nothing more. As such, its use is always somewhat different to each person. Here's how I understand them for the two languages in question:

In C++, an underscore usually indicates a private member variable.

In C#, I usually see it used only when defining the underlying private member variable for a public property. Other private member variables would not have an underscore. This usage has largely gone to the wayside with the advent of automatic properties though.

Before:

private string _name;
public string Name
{
    get { return this._name; }
    set { this._name = value; }
}

After:

public string Name { get; set; }
Thursday, June 3, 2021
 
John_BSDthos
answered 6 Months ago
33

Linus Torvalds - Linux Kernel coding style from Linus Torvalds :

LOCAL variable names should be short, and to the point. If you have some random integer loop counter, it should probably be called "i". Calling it "loop_counter" is non-productive, if there is no chance of it being mis-understood. Similarly, "tmp" can be just about any type of variable that is used to hold a temporary value.

If you are afraid to mix up your local variable names, you have another problem, which is called the function-growth-hormone-imbalance syndrome.

Thursday, August 26, 2021
 
Naveed S
answered 3 Months ago
94

On module level the second:

ReferenceToClass = MyClass

As a function argument, the first:

reference_to_class = MyClass

Friday, September 10, 2021
 
user852974
answered 3 Months ago
24

The C++ method will also contain your namespace (e.g. com.domain.your) and classname (e.g. YourActivity), it will look something like

JNIEXPORT jstring JNICALL Java_com_domain_your_YourActivity_native_1getParameters(JNIEnv * env, jclass clazz)

Note the C++ _1 equates to the _ in your Java method

Thursday, November 18, 2021
 
Rahul Sharma
answered 2 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share