development

변수 및 함수 이름에 대한 Python의 명명 규칙은 무엇입니까?

big-blog 2020. 9. 30. 09:18
반응형

변수 및 함수 이름에 대한 Python의 명명 규칙은 무엇입니까?


C # 배경에서 비롯된 변수 및 메서드 이름에 대한 명명 규칙은 일반적으로 camelCase 또는 PascalCase입니다.

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

Python에서는 위의 내용을 보았지만 밑줄도 사용하는 것을 보았습니다.

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

파이썬에 더 선호되고 명확한 코딩 스타일이 있습니까?


Python PEP 8을 참조하십시오 .

함수 이름은 소문자 여야하며 가독성을 높이기 위해 단어를 밑줄로 구분해야합니다.

mixedCase는 이미 일반적인 스타일 인 컨텍스트에서만 허용됩니다.

변수...

가독성을 높이기 위해 필요에 따라 단어를 밑줄로 구분 한 소문자로 함수 이름 지정 규칙을 사용하십시오.

개인적으로 나는 내 프로젝트 mixedCase보다 선호하기 때문에 이것에서 벗어납니다 lower_case.


Google Python 스타일 가이드 에는 다음과 같은 규칙이 있습니다.

module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name

비슷한 이름 지정 체계를 CLASS_CONSTANT_NAME


David Goodger ( "Code Like a Pythonista" 에서 )는 PEP 8 권장 사항을 다음과 같이 설명합니다.

  • joined_lower 함수, 메소드, 속성, 변수

  • joined_lower또는 ALL_CAPS상수

  • StudlyCaps 수업 용

  • camelCase 기존 규칙을 준수하기 위해서만


Python 코드에 대한 스타일 가이드가 인정 했듯이

파이썬 라이브러리의 명명 규칙은 약간 엉망이어서 완전히 일관 적이 지 않을 것입니다.

이것은 단지 Python의 표준 라이브러리 를 나타냅니다 . 그들이 얻을 수없는 경우 일관성, 다음이 거의 갖는 많은 희망은 일반적으로-부착 된-에 규칙에 대한 없습니다 모두 가, 파이썬 코드는 무엇입니까?

그것과 여기에서의 논의에서, 파이썬으로 넘어갈 때 변수와 함수에 대해 자바 나 C #의 (명확하고 잘 확립 된) 명명 규칙을 계속 사용하는 것은 끔찍한 죄 아니라는 것을 추론 할 것 입니다. 물론, 코드베이스 / 프로젝트 / 팀의 일반적인 스타일이 무엇이든간에 준수하는 것이 가장 좋습니다. Python 스타일 가이드에서 지적했듯이 내부 일관성이 가장 중요합니다.

저를 이단자로 해고 하셔도됩니다. :-) OP처럼 저는 "Pythonista"가 아닙니다.


PEP 8은 다른 답변이 보여으로,하지만, PEP 8은 표준 라이브러리에 대해서만 스타일 가이드이며, 그것은 오직 복음 거기로 물었다. 다른 코드 조각에 대한 PEP 8의 가장 빈번한 편차 중 하나는 특히 메서드에 대한 변수 이름 지정입니다. 단일 우세한 스타일은 없지만 mixedCase를 사용하는 코드의 양을 고려할 때 엄격한 인구 조사를 수행하려면 mixedCase가 포함 된 PEP 8 버전으로 끝날 것입니다. 매우 일반적인 PEP 8과의 다른 편차는 거의 없습니다.


언급했듯이 PEP 8은 lower_case_with_underscores변수, 메서드 및 함수 를 사용하도록 말합니다 .

나는 lower_case_with_underscores변수와 mixedCase메서드 및 함수에 사용하는 것을 선호하여 코드를 더 명확하고 읽기 쉽게 만듭니다. 따라서 Python의 "명시적인 것이 암시적인 것보다 낫다"와 "가독성이 중요하다"를 따르는


개인적으로 저는 클래스, mixedCase 메서드 및 함수에 CamelCase를 사용하려고합니다. 변수는 일반적으로 밑줄로 구분됩니다 (기억할 수있는 경우). 이렇게하면 모든 것이 똑같이 보이는 대신 정확히 내가 무엇을 부르고 있는지 한눈에 알 수 있습니다.


@JohnTESlade가 답변 한 내용에 대해 자세히 알아보십시오. Google의 Python 스타일 가이드 에는 꽤 깔끔한 권장 사항이 있습니다.

피해야 할 이름

  • 카운터 또는 반복자를 제외한 단일 문자 이름
  • 패키지 / 모듈 이름의 대시 (-)
  • \__double_leading_and_trailing_underscore__ names (Python에서 예약)

명명 규칙

  • "Internal" means internal to a module or protected or private within a class.
  • Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from). Prepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling).
  • Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module.
  • Use CapWords for class names, but lower_with_under.py for module names. Although there are many existing modules named CapWords.py, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait -- did I write import StringIO or from StringIO import StringIO?")

Guidelines derived from Guido's Recommendations enter image description here


Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.

I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething() than SomeClass.do_something(). If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.


There is a paper about this: http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf

TL;DR It says that snake_case is more readable than camelCase. That's why modern languages use (or should use) snake wherever they can.


The coding style is usually part of an organization's internal policy/convention standards, but I think in general, the all_lower_case_underscore_separator style (also called snake_case) is most common in python.


I personally use Java's naming conventions when developing in other programming languages as it is consistent and easy to follow. That way I am not continuously struggling over what conventions to use which shouldn't be the hardest part of my project!


Typically, one follow the conventions used in the language's standard library.

참고URL : https://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names

반응형