对于C#程序员编写Python咨询 [英] Advice for C# programmer writing Python

查看:205
本文介绍了对于C#程序员编写Python咨询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要在做C#开发,在过去几年,但最近开始做一些Python的(而不是铁的Python)的。但我不知道如果我所做的心理飞跃到Python ...我有种感觉我试图做的事情,我会在C#。

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#.

我如何能充分利用Python的优势有什么建议?

Any advice on how I can fully take advantage of Python?

或任何tips\tricks,要学的东西更多的事情需要提防?

Or any tips\tricks, things to learn more about, things to watch out for?

推荐答案

首先,检查 tgray的伦德斯特伦的建议。


  • 的Python是动态类型,所以不像C#,你不会
    查看类型,但是行为。您可能需要google一下鸭子
    打字。这意味着你不必应付拳击和
    拆箱。

  • 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是完全面向对象的,但语法并不
实施这一模式。您可以编写Python不使用
字类。

Python is fully object oriented, but the syntax does not enforce this paradigm. You can write Python without using the word "class".

与Python功能的GUI库无法与
C#的比较。检查 PyQt的,GTK或的wxPython

The GUI library featured with Python can't compare with C#'s. Check PyQt, GTK or wxPython libraries.

Python有很多的概念,你可能不熟悉:
名单解析,发电机(收益呢存在于C#
,但已不常用),装饰,元类等,不要
怕,你可以在Python程序没有他们。他们
只是聪明的工具,不是强制性的。

Python has a lot of concepts you may not be familiar with: list comprehensions, generators ("yield" does exist in C# but 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.

就像在C#,Python标准库是巨大的。总是在它当您遇到任何问题,
的样子。这是最
可能是有人解决它了。

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的使用后期绑定和可变标签。它太
早有人开始用语言来担心
吧,但要记住,有一天你会遇到变量
的行为,这似乎不合逻辑,你会
的检查。对于时刻:

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:

只要记住永远不要做到以下几点:

Just remember to never do the following:

def myfunc(my_list=[]) :
   # bla

相反:

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是跨平台的,喜欢写在Mac和Linux上的
    来说,如果你的愿望。

  • Python is cross platform, enjoy writing on Mac, and run on Linux, if you wish.

Python中没有设置复杂的IDE(你得到的 IDLE :-))。
如果你是一个Visual Studio瘾君子,检查格莱德。这是
没有Visual Studio的高级,但它仍然是一个不错的 RAD

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.

如果你想开发在Python一些Web应用程序,
记住,Python是不是.NET。如果你想比较,你必须添加一个网络
框架了。我喜欢 Django的

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并不需要一个巨大的IDE的工作。 赛特
记事本++ IDLE ,的凯特的gedit ...
轻量级编辑真的足够了。

Python does not need a huge IDE to work with. SciTE, Notepad++, IDLE, Kate, gedit... Lightweight editors are really sufficient.

Python的强制使用空格和换行,
你不能改变的压痕。你应该避免使用
缩进选项卡,然后选择空格代替。
空手镯相当于{}是关键字通行证。

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不强制私人增值经销商。你可以定义使用__(2下划线)在
中的变数名称的开头
私人变种,但它仍然在一些棘手的
方式旁路。通常的Python程序员承担种植成人
那些知道他们做了什么和交流。

Python does not enforce private vars. You can define a private var using "__" (2 underscore) at the beginning of the var 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使用迭代。很多。大把大把的。这样一来,
itertools模块里是你最好的朋友。

Python uses iteration. A lot. A lot of a lot. And so the itertools module is you best friend.

Python已经没有在建的代表。委托模块是
不是你想的。对于事件驱动编程,使用
GUI LIB(或代码模式自己,它不是
困难)。

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有一个解释:你可以测试几乎所有的东西,
直播。它应该始终处于运行状态旁边的文字
编辑。 Python的基本解释并不多,尝试 IPython的
的东西好吃。

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 IPython for something tasty.

关于Python,autodocumented:使用文档字符串在自己的代码
和咨询等的使用帮助()中的Python解释器

Python is autodocumented: use docstrings in your own code and consult other's using "help()" in the python interpreter


  • SYS:操纵系统功能

  • 操作系统:设置凭证,处理文件路径,重命名,递归文件散步等

  • shutil:批处理文件处理(如递归删除)

  • 回复:正则表达式

  • 的urllib和urllib2的:HTTP¨scri​​pting如下载,邮政/获取resquests等

  • 日期时间:操纵日期,时间和期限

  • 螺纹:你猜它

  • 的zlib:压缩

  • 泡菜:序列化

  • XML:解析/编写XML使用SAX或DOM

  • 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

有数百个模块。享受

的Python程序员使用foreach C#
环的大量等同,而且喜欢任何人:

Python coders use massively the equivalent of the foreach C# loop, and prefer it to any others :

基本迭代:

for item in collection:
    print str(item)

收藏可以是一个字符串,列表,元组...任何
迭代:任何对象定义。接下来()方法。有
了很多在Python iterables的。例如:一个典型的Python的成语
读取文件:

"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:

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:

创建过滤列表与列表理解:

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)

与上面相同,但值将在第一次迭代中再丢飞
产生。更多关于它href=\"http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement\">

Same as above, but the values will be generated on the fly at the first iteration then lost. More info about it here.

普通for循环

如果你想表达一个通常的for循环,可以用
的xrange()函数。的for(int i = 0; I< 5;我++)变为:

If you want to express a usual for loop, you can use the xrange() function. for (int i = 0; i < 5; i++) becomes:

for i in xrange(0,5) :

做,而相当于

有没有做虽然Python中。我从来没有错过它,但如果
你必须使用这个逻辑,做到以下几点:

There is no "Do While" in Python. I never missed it, but if you have to use this logic, do the following:

while True : # yes, this is an infinite loop. Crazy, hu ?

  # do your stuff

  if condition :
      break



开箱



交换变量:

a, b = b, a

多幽会:

以上只是我们所说的拆包的结果(这里
适用于元组)。一个简单的方法来解释它是你
能在一个变量任意序列的每个值直接分配给一个平等
号,一排:

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:

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, e.g :

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

这就是为什么如果你想获得一个指标而进行迭代,
Python的程序员使用下面的成语(枚举()是
标准功能):

And that's why if you want to get an index while iterating, Python coders use the following idioms (enumerate() is a standard function):

for index, value in enumerate(sequence) :
    print index, value

在功能开箱调用

这是高级应用,你可以,如果你烦恼跳过。

This is advanced use, you can skip 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 :-).

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



逻辑检查:



您可以检查您在C#中做的方式,但也有Python化
方式(更短,更清晰的: - )):

Logical checks:

You can check the way you do in C#, but there are "Pythonic" ways (shorter, clearer :-)):

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用大写的字):



Combo (print on one line all the words containing an "o" in uppercase ):

sentence = "It's a good day to write some code"
print " ".join([word.upper() for word in sentence.split() if "o" in word])

输出:GOOD一些代码

Output: "GOOD TO SOME CODE"

的Python程序员通常不检查,如果事情是可能的。
他们有点像查克·诺里斯。他们做到这一点。然后抓住
例外。通常情况下,你不检查文件是否存在,你
尝试打开它,并回滚如果失败:

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.

其他是在Python多种用途的世界。你会发现
别人如果,但经过后,除和的可能。

"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 thing
else :
    # this always happens unless you hit "break" in the loop

这适用于while循环太多,就算我们不尽可能多的使用
循环。

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#






如果你是好奇,这里是一堆先进的快速和
肮脏的(但好) Python的片段

这篇关于对于C#程序员编写Python咨询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆