给 C# 程序员编写 Python 的建议
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/683273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Advice for C# programmer writing Python
提问by Gern Blanston
I've mainly been doing C# development for the past few years but recently started to do a bit of Python (not Iron Python). But I'm not sure if I've made the mental leap to Python...I kind of feel I'm trying to do things as I would in C#.
过去几年我主要从事 C# 开发,但最近开始做一些 Python(不是 Iron Python)。但我不确定我是否已经在精神上飞跃到 Python ......我有点觉得我正在尝试像在 C# 中那样做事。
Any advice on how I can fully take advantage of Python?
关于如何充分利用 Python 的任何建议?
Or any tips\tricks, things to learn more about, things to watch out for?
或者任何提示\技巧、需要了解的更多信息、需要注意的事项?
回答by Van Gale
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 CPythonand don't do any more C# coding until you feel like you have a grasp of Python.
如果您是通过采取小的增量步骤来更好地学习一门新语言的人,那么我建议您使用IronPython。否则,请使用常规CPython并且不要再进行任何 C# 编码,直到您觉得自己掌握了 Python。
回答by jle
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.
我建议找一个好的编辑器,这样你就不会被空格咬住了。为简单起见,我只使用 ActivePython 的包Link,其中包括一个编辑器和所有 win32api 库。如果您一直在使用 C#,那么了解它们会很有趣。Python 中的 win32api 可以更简单一点。您不需要执行整个 DDLImport 操作。下载 ActivePython(CPython 自带的),打开它,然后开始在控制台输入一些东西。使用 C# 后,您将很容易上手。对于一些更有趣的 Python 花絮,请尝试ActiveState 代码,它具有各种秘诀,可以让您非常简单地看到可以使用 Python 完成的不同事情。
回答by Vilmorin
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.
如果您不熟悉编程,我会推荐Mark Pilgrim 的“Dive into Python”一书。它以一种易于理解如何应用 Python 技术和习语来构建实际应用程序的方式来解释 Python。
回答by Can Berk Güder
Start by reading The Zen of Python
从阅读Python 之禅开始
You can read it at the link above, or just type import this
at the Python prompt. =)
您可以在上面的链接中阅读它,也可以import this
在 Python 提示符下输入。=)
Take advantage of Python features not offered* by C#
利用 C# 未提供*的 Python 功能
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.
所以你不用重新发明轮子。不要试图阅读整篇文章,即使快速浏览一下 TOC 也可以为您节省大量时间。
* 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.
* 我知道 C# 已经具有其中的一些特性,但从我所见,它们要么非常新,要么不常被 C# 开发人员使用。如果我错了,请纠正我。
回答by tgray
In case you haven't heard about it yet, Dive Into Pythonis a great place to start for anyone learning Python. It also has a bunch of Tips & Tricks.
如果您还没有听说过它,Dive Into Python是任何学习 Python 的人的绝佳起点。它还有一堆提示和技巧。
回答by Stefan Lundstr?m
- 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.
- 避免使用类。使用字典、集合、列表和元组。
- 禁止使用 setter 和 getter。
- 除非您确实需要,否则不要使用异常处理程序 - 让它以风格崩溃。
- Pylint 可以成为您更多 Python 风格编码风格的朋友。
- 准备就绪后 - 查看列表推导式、生成器和 lambda 函数。
回答by theycallmemorty
If you have programming experience and don't feel like spending money I'd recommend How to Think Like a Computer Scientist in Python.
如果您有编程经验并且不想花钱,我会推荐How to Think Like a Computer Scientist in Python。
回答by e-satis
First, check tgray'sand Lundstr?m'sadvice.
首先,查看tgray和Lundstr?m 的建议。
Then, some things you may want to know:
然后,您可能想知道一些事情:
Python is dynamically typed, so unlike C#, you will not check type, but behavior. You may want to google about duck typing. It implies you do not have to deal with boxing and unboxing.
Python is fully object oriented, but the syntax does not enforce this paradigm. You can write Python without using the word "class".
The GUI library featured with Python can't compare with C#'s. Check PyQt, GTK or wxPythonlibraries.
Python has a lot of concepts you may not be familiar with: list comprehensions, generators ("yield" does exist in C#, but it is not used much), decorators, metaclasses, etc. Don't be afraid; you can program in Python without them. They are just smart tools, not mandatory.
Like in C#, the Python standard library is huge. Always look at it when you encounter any problem. It is most likely that someone solved it already.
Python use LATE binding and variable labels. It's far too early for somebody starting with the language to worry about it, but remember that one day you will encounter a behavior with variables that SEEMS illogical, and you'll have to check that. For the moment:
Python 是动态类型的,因此与 C# 不同,您不会检查类型,而是检查行为。你可能想谷歌一下鸭子打字。这意味着您不必处理装箱和拆箱。
Python 是完全面向对象的,但语法并不强制这种范式。您可以在不使用“类”一词的情况下编写 Python。
Python 有很多你可能不熟悉的概念:列表推导式、生成器(“yield”在 C# 中确实存在,但用得不多)、装饰器、元类等。不要害怕;你可以在没有它们的情况下用 Python 编程。它们只是智能工具,不是强制性的。
就像在 C# 中一样,Python 标准库非常庞大。当您遇到任何问题时,请务必查看它。很可能已经有人解决了。
Python 使用 LATE 绑定和变量标签。对于开始使用该语言的人来说担心它为时过早,但请记住,有一天您会遇到带有似乎不合逻辑的变量的行为,您必须检查一下。目前:
Just remember to never do the following:
请记住永远不要做以下事情:
def myfunc(my_list=[]) :
# bla
Instead:
反而:
def myfunc(my_list=()) :
my_list = list(my_list)
And you'll be good. There is a good reason for that, but that's not the point :-)
你会很好的。这是有充分理由的,但这不是重点:-)
Python is cross platform, enjoy writing on Mac, and run on Linux, if you wish.
Python is not provided with a complex IDE (you got IDLE:-)). If you are a Visual Studio addict, check Glade. This is not as advanced as Visual Studio, but it's still a good RAD.
If you want to develop some web application in Python, remember that Python is not .NET. You must add a web framework to it if you want to compare. I like Django.
Python does not need a huge IDE to work with. SciTE, Notepad++, IDLE, Kate, gedit... Lightweight editors are really sufficient.
Python enforces indentation using spaces and line break, you can't change that. You should avoid using tabs for indenting and choose spaces instead. The equivalent of empty bracelets {} is the keyword "pass".
Python does not enforce private variables. You can define a private var using "__" (two underscores) at the beginning of the variable name, but it's still bypassable in some tricky ways. Python usually assume programmers are grown adults that know what they do and communicate.
Python uses iteration. A lot. A lot of a lot. And so the itertools module is you best friend.
Python has no built in delegates. The delegate module is not what you think. For event-driven programming, use a GUI lib (or code the pattern yourself, it's not that difficult).
Python has an interpreter: you can test almost anything, live. It should always be running next to your text editor. Python basic interpreter is not much, try IPythonfor something tasty.
Python is autodocumented: use docstrings in your own code and consult other's using "help()" in the python interpreter
Python 是跨平台的,喜欢在 Mac 上写作,如果你愿意,可以在 Linux 上运行。
Python 没有提供复杂的 IDE(你有空闲:-))。如果您是 Visual Studio 上瘾者,请查看Glade。这不如 Visual Studio 先进,但它仍然是一个很好的RAD。
如果您想用 Python 开发一些 Web 应用程序,请记住 Python 不是 .NET。如果要比较,必须向其添加 Web 框架。我喜欢姜戈。
Python 不需要庞大的 IDE 即可使用。SciTE、 Notepad++、IDLE、Kate、gedit……轻量级编辑器真的够用了。
Python 使用空格和换行符强制缩进,你不能改变它。您应该避免使用制表符进行缩进,而是选择空格。相当于空手镯{}的是关键字“pass”。
Python 不强制执行私有变量。您可以在变量名的开头使用“__”(两个下划线)定义私有变量,但它仍然可以通过一些棘手的方式绕过。Python 通常假设程序员是成年人,知道他们做什么和交流。
Python 使用迭代。很多。很多很多。所以 itertools 模块是你最好的朋友。
Python 没有内置的委托。委托模块不是你想的那样。对于事件驱动编程,请使用 GUI 库(或自己编写模式代码,这并不难)。
Python 有一个解释器:你可以实时测试几乎任何东西。它应该始终在您的文本编辑器旁边运行。Python 基本解释器并不多,尝试IPython以获得一些美味。
Python 是自动记录的:在您自己的代码中使用文档字符串,并在 Python 解释器中使用“help()”咨询其他人
Module basics:
模块基础:
- sys: manipulate system features
- os: set credential, manipulate file paths, rename, recursive file walk, etc
- shutil: batch file processing (such as recursive delete)
- re: regexp
- urllib and urllib2: HTTP¨scripting like downloading, post / get resquests, etc.
- datetime: manipulate date, time AND DURATION
- thread: you guess it
- zlib: compression
- pickle: serialization
- xml: parsing / Writing XML with SAX or DOM
- sys:操纵系统功能
- os:设置凭据、操作文件路径、重命名、递归文件遍历等
- Shutil:批处理文件处理(如递归删除)
- 回复:正则表达式
- urllib 和 urllib2:HTTP 脚本,如下载、发布/获取请求等。
- datetime:操作日期、时间和持续时间
- 主题:你猜对了
- zlib:压缩
- 泡菜:序列化
- xml:使用 SAX 或 DOM 解析/编写 XML
There are hundreds of modules. Enjoy.
有数百个模块。享受。
Some typical ways to do things in Python:
在 Python 中做事的一些典型方法:
Loops:
循环:
Python coders use massively the equivalent of the foreach
C#
loop, and prefer it to any others:
Python 编码人员大量使用foreach
C# 循环的等价物,并且比其他任何人更喜欢它:
Basic iterations:
基本迭代:
for item in collection:
print str(item)
"collection" can be a string, a list, a tuple... Any iterable: any object defining the .next() method. There are a lot of iterables in Python. E.g: a typical Python idiom to read files:
“集合”可以是字符串、列表、元组……任何可迭代对象:定义 .next() 方法的任何对象。Python 中有很多可迭代对象。例如:读取文件的典型 Python 习惯用法:
for line in open("/path/to/file") :
print line
A shortcut to the for loop is called "list comprehension". It's a way to create an new iterable in one line:
for 循环的快捷方式称为“列表理解”。这是一种在一行中创建新迭代的方法:
Creating a filtered list with list comprehension:
使用列表理解创建过滤列表:
my_list = [item for item in collection if condition]
Creating a new list with a list comprehension:
使用列表理解创建新列表:
my_list = [int(item) * 3 for item in collection]
Creating a new generator with a list comprehension:
使用列表理解创建一个新的生成器:
my_list = (int(item) * 3 for item in collection)
Same as above, but the values will be generated on the fly at the first iteration then lost. More information about it here.
与上面相同,但这些值将在第一次迭代时即时生成,然后丢失。关于它的更多信息在这里。
Ordinary for loop
普通for循环
If you want to express a usual for loop, you can use the
xrange() function. for (int i = 0; i < 5; i++)
becomes:
如果要表达通常的 for 循环,可以使用 xrange() 函数。for (int i = 0; i < 5; i++)
变成:
for i in xrange(0,5) :
do while equivalent
do while 等效
There is no "Do While" in Python. I never missed it, but if you have to use this logic, do the following:
Python 中没有“Do While”。我从未错过它,但如果您必须使用此逻辑,请执行以下操作:
while True : # Yes, this is an infinite loop. Crazy, hu?
# Do your stuff
if condition :
break
Unpacking
开箱
Swapping variables:
交换变量:
a, b = b, a
Multiple assignations:
多重分配:
The above is just a result of what we call "unpacking" (here applied to a tuple). A simple way to explain it is that you can assign each value of any sequence directly to an equal number a variables, in one row:
以上只是我们所谓的“解包”(这里适用于元组)的结果。一种简单的解释方法是,您可以将任何序列的每个值直接分配给相同数量的 a 变量,在一行中:
animal1, animal2, animal3, animal4 = ["cow", "dog", "bird", "fish"]
This has a lot of implications. While iterating on a multidimensional array, you normally get each sub sequence one by one then use it, for example:
这有很多含义。在对多维数组进行迭代时,您通常会一一获取每个子序列然后使用它,例如:
agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")]
for person in agenda:
print person[0], person[1]
But with unpacking, you can assign the values directly to variables as well:
但是通过解包,您也可以将值直接分配给变量:
agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")]
for name, lastname in agenda:
print name, lastname
And that's why if you want to get an index while iterating, Python coders use the following idioms (enumerate() is a standard function):
这就是为什么如果您想在迭代时获取索引,Python 编码人员使用以下习语(enumerate() 是标准函数):
for index, value in enumerate(sequence) :
print index, value
Unpacking in functions calls
在函数调用中解包
This is advanced use, and you can skip it if it bothers you.
这是高级用法,如果它打扰您,您可以跳过它。
You can unpack values using the sign "*" to use a sequence directly in a function call. E.g:
您可以使用符号“*”解包值以直接在函数调用中使用序列。例如:
>>> foo(var1, var1, var3) :
print var1, var2
print var3
>>> seq = (3.14, 42, "yeah")
>>> foo(*seq)
3.14 42
yeah
There is even more than that. You can unpack a dictionary as
named variables, and write function prototypes with *
,
**
to accept an arbitrary number of arguments. But it not
used enough to deserve to make this post even longer :-).
还有更多。您可以将字典解包为命名变量,并使用*
,
编写函数原型**
以接受任意数量的参数。但它的使用还不够,不值得让这篇文章更长:-)。
String formatting:
字符串格式:
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"}
Slicing an iterable:
切片可迭代:
You can get any part of an iterable using a very concise syntax:
您可以使用非常简洁的语法获取可迭代对象的任何部分:
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
Logical checks:
逻辑检查:
You can check the way you do in C#, but there are "Pythonic" ways (shorter, clearer :-)):
您可以检查您在 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)
Combo (print on one line all the words containing an "o" in uppercase ):
组合(在一行上打印所有包含大写“o”的单词):
sentence = "It's a good day to write some code"
print " ".join([word.upper() for word in sentence.split() if "o" in word])
Output: "GOOD TO SOME CODE"
输出:“对某些代码很好”
Easier to ask for forgiveness than permission
请求原谅比许可更容易
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:
Python 编码人员通常不会检查是否有可能。他们有点像查克·诺里斯。他们这样做。然后捕获异常。通常,您不会检查文件是否存在,而是尝试打开它,如果失败则回滚:
try :
f = open(file)
except IOerror :
print "no file here !"
Of course Chuck Norris never uses excepts since he never fails.
当然,Chuck Norris 从不使用异常,因为他从不失败。
The else clause
else 子句
"Else" is a world of many uses in Python. You will find "else" after "if", but after "except" and "for" as well.
“Else”是 Python 中的一个用途广泛的世界。您会在“if”之后找到“else”,但也会在“except”和“for”之后找到。
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.
这也适用于“while”循环,即使我们不经常使用这个循环。
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.
如果你很好奇,这里有一堆高级的快速和肮脏(但很好)的Python 片段。
回答by Lakshman Prasad
And then something you can benefit from:
然后你可以从中受益:
IPythonshell: Auto completion in the shell. It does batch operations, adds a ton of features, logging and such. >>> Play with the shell - always!
IPythonshell:在 shell 中自动完成。它执行批处理操作,添加大量功能,日志记录等。>>> 玩 shell - 永远!
easy_install / pip: So nice and an easy way to install a 3rd party Python application.
easy_install / pip:安装 3rd 方 Python 应用程序的好方法和简单方法。
回答by RonaldHobbs
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.
我也和你一样,在我的大部分工作中仍然使用 C#,但在其他项目中越来越多地使用 Python。
@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:
@e-satis 可能彻底了解 Python,他的所有建议都是一流的。从我的角度来看,对我来说最大的不同是以下几点:
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.
口译员。它就像直接窗口,除了 10^10 更好。由于 Python 的工作方式,您不需要 C# 在运行之前放入的所有包袱和垃圾;你可以简单地敲几行,看看事情是如何运作的。
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.
我通常有一个空闲实例,在那里我只是抛出片段,因为我正在研究语言中的各个位如何在我编辑我的文件时工作......例如,忙于研究如何进行地图调用一个列表,但我不是 100% 使用我应该使用的 lambda... 用几行代码进入 IDLE,看看它是如何工作的以及它做了什么。
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.
最后,喜欢 Python 的冗长,我并不是说冗长冗长的意思,而是正如 e-satis 指出的那样,使用“in”、“is”、“for”等动词会让人感到厌烦。
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.
如果你在 C# 中做了大量的反射工作,当你看到 Python 中同样的东西是多么的简单时,你会想哭。
Good luck with it.
祝你好运。