Python을 작성하는 C # 프로그래머를위한 조언
저는 주로 지난 몇 년 동안 C # 개발을 해왔지만 최근에는 약간의 Python (Iron Python이 아님)을 시작했습니다. 하지만 정신적으로 파이썬으로 도약했는지 확실하지 않습니다 ... 저는 C # 에서처럼 일을하려고 노력하고 있다고 느낍니다.
파이썬을 완전히 활용할 수있는 방법에 대한 조언이 있습니까?
또는 팁 / 트릭, 자세히 알아보기,주의해야 할 사항이 있습니까?
먼저 tgray 와 Lundström의 조언을 확인하십시오 .
그런 다음 알고 싶은 몇 가지 사항 :
Python은 동적으로 형식화되므로 C #과 달리 형식이 아닌 동작을 확인합니다. 오리 타이핑에 대해 Google을 검색해보세요. 그것은 당신이 권투와 개봉을 다룰 필요가 없다는 것을 의미합니다.
파이썬은 완전히 객체 지향적이지만 구문은이 패러다임을 강제하지 않습니다. "class"라는 단어를 사용하지 않고도 Python을 작성할 수 있습니다.
Python에 포함 된 GUI 라이브러리는 C #과 비교할 수 없습니다. PyQt , GTK 또는 wxPython 라이브러리를 확인하십시오 .
파이썬에는 여러분이 익숙하지 않을 수있는 많은 개념이 있습니다 : 목록 이해력, 생성기 ( "yield"는 C #에 존재하지만 많이 사용되지 않음), 데코레이터, 메타 클래스 등. 두려워하지 마십시오. 그것들없이 파이썬으로 프로그래밍 할 수 있습니다. 필수가 아닌 스마트 도구 일뿐입니다.
C #과 마찬가지로 Python 표준 라이브러리는 엄청납니다. 문제가 발생하면 항상 확인하십시오. 누군가 이미 해결했을 가능성이 큽니다.
Python은 LATE 바인딩 및 변수 레이블을 사용합니다. 언어로 시작하는 누군가가 그것에 대해 걱정하기에는 너무 이르지만 언젠가는 비논리적으로 보이는 변수가있는 동작을 만나게되며이를 확인해야합니다. 순간:
다음은 절대 수행하지 마십시오.
def myfunc(my_list=[]) :
# bla
대신 :
def myfunc(my_list=()) :
my_list = list(my_list)
그리고 당신은 잘 될 것입니다. 그럴만 한 이유가 있지만 그게 요점이 아닙니다 :-)
Python은 크로스 플랫폼이며 Mac에서 작성을 즐기고 원한다면 Linux에서 실행됩니다.
Python은 복잡한 IDE와 함께 제공되지 않습니다 ( IDLE :-)). Visual Studio 중독자 인 경우 Glade를 확인하십시오 . 이것은 Visual Studio만큼 발전된 것은 아니지만 여전히 좋은 RAD 입니다.
Python으로 일부 웹 애플리케이션을 개발하려면 Python이 .NET이 아님을 기억하십시오. 비교하려면 웹 프레임 워크를 추가해야합니다. 나는 장고를 좋아한다 .
Python은 작업하기 위해 거대한 IDE가 필요하지 않습니다. SciTE , Notepad ++ , IDLE , Kate , gedit ... 경량 편집기만으로도 충분합니다.
파이썬은 공백과 줄 바꿈을 사용하여 들여 쓰기를 적용합니다. 변경할 수 없습니다. 들여 쓰기에 탭을 사용하지 말고 대신 공백을 선택해야합니다. 빈 팔찌 {}에 해당하는 것은 키워드 "pass"입니다.
Python은 개인 변수를 적용하지 않습니다. 변수 이름의 시작 부분에 "__"(두 개의 밑줄)를 사용하여 private var를 정의 할 수 있지만 몇 가지 까다로운 방법으로 우회 할 수 있습니다. 파이썬은 보통 프로그래머가 자신이하는 일과 의사 소통을 잘 아는 성인이라고 가정합니다.
파이썬은 반복을 사용합니다. 많이. 아주 많이. 그래서 itertools 모듈은 가장 친한 친구입니다.
Python에는 기본 제공 델리게이트가 없습니다. 델리게이트 모듈은 당신이 생각하는 것과 다릅니다. 이벤트 중심 프로그래밍의 경우 GUI lib를 사용하십시오 (또는 패턴을 직접 코딩하십시오. 그렇게 어렵지 않습니다).
Python에는 인터프리터가 있습니다. 거의 모든 것을 실시간으로 테스트 할 수 있습니다. 항상 텍스트 편집기 옆에서 실행되어야합니다. 파이썬 기본 인터프리터는 많지 않습니다 . 맛있는 것을 위해 IPython 을 사용해보십시오 .
파이썬은 자동 문서화됩니다 : 자신의 코드에서 독 스트링을 사용하고 파이썬 인터프리터에서 "help ()"를 사용하여 다른 사람에게 문의하십시오.
모듈 기본 사항 :
- sys : 시스템 기능 조작
- os : 자격 증명 설정, 파일 경로 조작, 이름 바꾸기, 재귀 적 파일 워크 등
- shutil : 배치 파일 처리 (예 : 재귀 삭제)
- re : 정규식
- urllib 및 urllib2 : 다운로드, 게시 / 요청 받기 등과 같은 HTTP¨ 스크립팅
- datetime : 날짜, 시간 및 DURATION 조작
- 스레드 : 당신은 그것을 추측
- zlib : 압축
- pickle : 직렬화
- xml : SAX 또는 DOM으로 XML 구문 분석 / 작성
수백 개의 모듈이 있습니다. 즐겨.
Python에서 작업을 수행하는 몇 가지 일반적인 방법 :
루프 :
Python 코더는 foreach
C # 루프에 해당하는 것을 엄청나게 사용하며 다른 것보다 선호합니다.
기본 반복 :
for item in collection:
print str(item)
"컬렉션"은 문자열, 목록, 튜플이 될 수 있습니다. 모든 반복 가능 : .next () 메서드를 정의하는 모든 객체. 파이썬에는 많은 이터 러블이 있습니다. 예 : 파일을 읽는 일반적인 Python 관용구 :
for line in open("/path/to/file") :
print line
for 루프에 대한 바로 가기를 "목록 이해"라고합니다. 한 줄에 새 이터 러블을 만드는 방법입니다.
목록 이해력으로 필터링 된 목록 만들기 :
my_list = [item for item in collection if condition]
목록 이해력으로 새 목록 만들기 :
my_list = [int(item) * 3 for item in collection]
목록 이해력으로 새 생성기 만들기 :
my_list = (int(item) * 3 for item in collection)
위와 동일하지만 값은 첫 번째 반복에서 즉석에서 생성 된 다음 손실됩니다. 여기 에 대한 자세한 정보 .
일반 for 루프
일반적인 for 루프를 표현하려면 xrange () 함수를 사용할 수 있습니다. for (int i = 0; i < 5; i++)
된다 :
for i in xrange(0,5) :
동등하게하다
Python에는 "Do While"이 없습니다. 나는 그것을 놓친 적이 없지만이 논리를 사용해야하는 경우 다음을 수행하십시오.
while True : # Yes, this is an infinite loop. Crazy, hu?
# Do your stuff
if condition :
break
포장 풀기
변수 교체 :
a, b = b, a
다중 할당 :
위의 내용은 우리가 "unpacking"(여기서는 튜플에 적용됨)이라고 부르는 결과입니다. 이를 설명하는 간단한 방법은 모든 시퀀스의 각 값을 한 행에서 동일한 수의 변수에 직접 할당 할 수 있다는 것입니다.
animal1, animal2, animal3, animal4 = ["cow", "dog", "bird", "fish"]
이것은 많은 의미를 가지고 있습니다. 다차원 배열에서 반복하는 동안 일반적으로 각 하위 시퀀스를 하나씩 가져 와서 사용합니다. 예를 들면 다음과 같습니다.
agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")]
for person in agenda:
print person[0], person[1]
그러나 압축을 풀면 값을 변수에 직접 할당 할 수도 있습니다.
agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")]
for name, lastname in agenda:
print name, lastname
그래서 반복하는 동안 인덱스를 얻으려면 Python 코더가 다음 관용구를 사용합니다 (enumerate ()는 표준 함수입니다).
for index, value in enumerate(sequence) :
print index, value
함수 호출에서 풀기
이것은 고급 사용이며 귀찮 으면 건너 뛸 수 있습니다.
"*"기호를 사용하여 값을 압축 해제하여 함수 호출에서 시퀀스를 직접 사용할 수 있습니다. 예 :
>>> foo(var1, var1, var3) :
print var1, var2
print var3
>>> seq = (3.14, 42, "yeah")
>>> foo(*seq)
3.14 42
yeah
그 이상이 있습니다. 당신은 이름 변수,와 쓰기 함수 프로토 타입으로 사전을 풀 수 *
, **
인수의 임의의 수를 수용 할 수 있습니다. 그러나이 게시물을 더 길게 만들만큼 충분히 사용되지 않았습니다. :-).
문자열 형식 :
print "This is a %s on %s about %s" % ("post", "stackoverflow", "python")
print "This is a %(subject)s on %(place)s about %(about)s" % {"subject" : "post", "place" : "stackoverflow", "about" : "python"}
이터 러블 슬라이스 :
매우 간결한 구문을 사용하여 이터 러블의 모든 부분을 가져올 수 있습니다.
print "blebla"[2:4] # Print "eb"
last = string[:-1] # Getting last element
even = (0,1,2,3,4,5,6,7,8,9)[::2] # Getting evens only (third argument is a step)
reversed = string[::-1] # Reversing a string
논리적 검사 :
C #에서 수행하는 방식을 확인할 수 있지만 "Pythonic"방식이 있습니다 (짧고 명확하게 :-)).
if 1 in (1, 2, 3, 4) : # Check en element is in a sequence
if var : # check is var is true. Var == false if it's False, 0, (), [], {} or None
if not var : # Contrary of above
if thing is var: # Check if "thing" and "var" label the same content.
if thing is None : # We use that one because None means nothing in Python (almost null)
콤보 ( "o"를 대문자로 포함하는 모든 단어를 한 줄에 인쇄) :
sentence = "It's a good day to write some code"
print " ".join([word.upper() for word in sentence.split() if "o" in word])
출력 : "GOOD TO SOME CODE"
허락보다 용서를 구하기가 더 쉽다
Python coders usually don't check if something is possible. They are a bit like Chuck Norris. They do it. Then catch the exception. Typically, you don't check if a file exists, you try to open it, and roll back if it fails:
try :
f = open(file)
except IOerror :
print "no file here !"
Of course Chuck Norris never uses excepts since he never fails.
The else clause
"Else" is a world of many uses in Python. You will find "else" after "if", but after "except" and "for" as well.
for stuff in bunch :
# Do things
else :
# This always happens unless you hit "break" in the loop
This works for "while" loop too, even if we do not use this loop as much.
try :
# A crazy stuff
except ToCrazyError :
# This happens if the crazy stuff raises a ToCrazyError Exception
else :
# This will happen if there is no error so you can put only one line after the "try" clause
finally :
# The same as in C#
If you are curious, here is a bunch of advanced quick and dirty (but nice) Python snippets.
- Refrain from using classes. Use dictionaries, sets, list and tuples.
- Setters and getters are forbidden.
- Don't have exception handlers unless you really need to - let it crash in style.
- Pylint can be your friend for more pythonish coding style.
- When you're ready - check out list comprehensions, generators and lambda functions.
If you are not new to programming, I would recommend the book "Dive into Python" by Mark Pilgrim. It explains Python in a way that makes it easy to understand how Python techniques and idioms can be applied to build practical applications.
Start by reading The Zen of Python
You can read it at the link above, or just type import this
at the Python prompt. =)
Take advantage of Python features not offered* by C#
Such as duck-typing, metaclasses, list comprehension, etc.*
Write simple programs just to test these features. You'll get used (if not addicted) to them in no time.
Look at the Python Standard Library
So you don't reinvent the wheel. Don't try to read the whole thing, even a quick look at the TOC could save you a lot of time.
* I know C# already has some of these features, but from what I can see they're either pretty new or not commonly used by C# developers. Please correct me if I'm wrong.
In case you haven't heard about it yet, Dive Into Python is a great place to start for anyone learning Python. It also has a bunch of Tips & Tricks.
If you are someone who is better learning a new language by taking small incremental steps then I would recommend using IronPython. Otherwise use regular CPython and don't do any more C# coding until you feel like you have a grasp of Python.
I would suggest getting a good editor so that you don't get bitten by whitespace. For simplicity, I just use ActivePython's packages Link, which include an editor and all of the win32api libraries. They are pretty fun to get into if you have been using C#. The win32api in Python can be a little bit simpler. You don't need to do the whole DDLImport thing. Download ActivePython (which comes with CPython), open it up, and start entering some stuff at the console. You will pick it up fairly easy after using C#. For some more interesting Python tidbits, try ActiveState code, which has all sorts of recipes, which can allow you to very simply see different things that you can do with Python.
I'm pretty much in your shoes too, still using C# for most of my work, but using Python more and more for other projects.
@e-satis probably knows Python inside-out and all his advice is top-notch. From my point of view what made the biggest difference to me was the following:
Get back into functional. not necessarily spaghetti code, but learning that not everything has to be in an object, nor should it be.
The interpreter. It's like the immediate window except 10^10 better. Because of how Python works you don't need all the baggage and crap C# makes you put in before you can run things; you can just whack in a few lines and see how things work.
I've normally got an IDLE instance up where I just throw around snippets as I'm working out how the various bits in the language works while I'm editing my files... e.g. busy working out how to do a map call on a list, but I'm not 100% on the lambda I should use... whack in a few lines into IDLE, see how it works and what it does.
And finally, loving into the verbosity of Python, and I don't mean that in the long winded meaning of verbosity, but as e-satis pointed out, using verbs like "in", "is", "for", etc.
If you did a lot of reflection work in C# you'll feel like crying when you see how simple the same stuff is in Python.
Good luck with it.
If you have programming experience and don't feel like spending money I'd recommend How to Think Like a Computer Scientist in Python.
And then something you can benefit from:
IPython shell: Auto completion in the shell. It does batch operations, adds a ton of features, logging and such. >>> Play with the shell - always!
easy_install / pip: So nice and an easy way to install a 3rd party Python application.
참고URL : https://stackoverflow.com/questions/683273/advice-for-c-sharp-programmer-writing-python
'Program Tip' 카테고리의 다른 글
여러 기준으로 Directory.EnumerateFiles를 필터링하는 방법은 무엇입니까? (0) | 2020.10.26 |
---|---|
Rails text_area 크기 (0) | 2020.10.26 |
트랜잭션 로그 비활성화 (0) | 2020.10.25 |
모듈을 파이썬으로 "다시 가져 오기"하는 방법, 가져 오기 후 코드 변경 (0) | 2020.10.25 |
쉼표 또는 세미콜론이있는 CSV? (0) | 2020.10.25 |