python变得越来越重要,尤其是作为一个十分出色的script语言。所以有必要学习一下基本的Python知识。
一,Wiki
http://en.wikipedia.org/wiki/Python_(programming_language):
The core philosophy of the language is summarized by the document "PEP 20 (The Zen of Python)", which includes aphorisms such as:[33]
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Readability counts.
python 目前有两个release版本在同时不断update,一个是2.X系列,一个是3.X系列,由于这两者不相互兼容,同时Python已经得到了多年的广泛使用,所以虽然3.X是Python的未来,但是基于实际practice不得不同时提供对以前基本Pyhton保持兼容的2.X。
(我们说各种语言都有自己的优势,C/C++的优势就在于其效率、灵活,即其对machine更加的“友好”,Python或者Java之类的主要在于其对programmer更加友好,当然两者也都在不断的全面evolve自己,向两方面都好的方向在努力。所以我们学习C/C++就主要应该侧重于对于效率灵活性方面特性的学习,像指针、内存的动态分配等,而不是为了简单的完成一些通用任务,学习Python等则主要是为了完成一些例行的任务,提高我们开发的效率,快速的完成一个任务,而不是为了优化某一个性能。
C/C++就像是飞机/大炮这样的重武器,powerful但是相对比较笨重,需要我们投入的coding时间比较长,而Python则像一把瑞士军刀,帮助我们小巧而方便的解决经常碰到的问题。
要明白,没有必要去盲目的成为一种语言的崇拜者,或者觉得某一种语言不好。重要的是,这些对你来说都是工具TOOLS,你的目的不是制造这些TOOLS,你的目的是又好有快的使用这些tools去完成自己的任务。)
官网摘要:
(1) applications such as:
Network Programming
In addition to the web and internet support described above, Python also provides support for lower level network programming:
- Easy-to-use socket interface.
- Twisted Python, a framework for asynchronous network programming.
(2) Learning
Before getting started, you may want to find out whichIDEs andtexteditors are tailored to makePython editing easy, browse the list of introductory books, or look at code samples that you might findhelpful.
There is a list of tutorials suitable for experienced programmers on theBeginnersGuide/Tutorials page. There is also a list ofresources in other languageswhich might be useful if English is not your first language.
The online documentationis your first port of call for definitive information. There is a fairly brief tutorial that gives you basic information about the language andgets you started. You can follow this by looking at the library reference for a full description of Python's many libraries and the language reference for a complete (though somewhat dry) explanation of Python's syntax.If you are looking for common Python recipes and patterns, you can browse theActiveState Python Cookbook
(3) Looking for Something Specific?
If you want to know whether a particular application, or a librarywith particular functionality, is available in Python there are anumber of possible sources of information. The Python web siteprovides a Python Package Index(also known as the Cheese Shop, a reference to the Monty Pythonscript of that name).There is also asearch page for a number of sources of Python-relatedinformation. Failing that, justGoogle for a phrase including the word ''python''and you may well get the result you need.If all else fails, ask on thepython newsgroupand there's a good chance someone will put you on the right track.
20140406:
这两天多的时间主要用来学习Python,主要是把《A byte of Python》看完,并实际的一边看着一边动手去完成其中的大部分示例程序。
因为我最近也在思考,像我这样的,已经有了一定的编程基础,勉强熟悉、掌握了基本的一些概念,写过一定量的代码了,在重新需要解决一个project需要重新回顾或者是学习一门较为相似的语言的时候,效率较高的学习方式到底应该是什么?现在作为有一定经验的programmer,应该如何更加modern的认识PROGRAMMING LANGUAGE?
一般的都是基本的从基础开始:基本数据类型、如何写出第一个示例程序,control flow statement( if, for, while), function, reusability相关的模块化组织方式, OO下的CLASS、继承。接着便是如何使用一些库。显然库将是在我们实际工作中扮演重要角色的元素。我们必须要对全局有那些库有了解,同时对于重要的库必须要有基本的更加深入的认识。
对于任何一门成熟而流行的语言,其强大性必然是建立在它能够满足大量的编程需求的基础上的,所以入门之后the next ste必然就是在实践中不断的学习掌握一些更加专门的trick。
看这种纯粹的技术性的书籍时还是会较为疲惫的,很难以较为长时间的focus attention。同时可以想见无论如何必须要加以总结才能不至于看完了又全部交还给了history memory!加油!
Python has shown her beauty and elegance, now it is your duty to chase her!
Go!
建议的学习roadmap 是先学习python自身核心的statement 和data structure然后逐步的学习各自特性,由于python良好的o正交性,我们可以较好的各个击破,掌握其基本特征!
Notes:
1 全书总评:这本书像一般的较好的入门书一样,对于一些最基本的东西讲的十分的细致。
同时还算全面涉及了较多的基础内容。但是确实也知识最最基本的introduction,有许多的内容,像Set,OO,lambda,decorator等等这些较为重要的内容居然基本上都是寥寥数语就一代而过了,这显然意味着我们还是需要接下来要以https://docs.python.org/2.7/index.html中的文档内容加以进一步了解的。标准库的学习也可以借助于http://pymotw.com/2/index.html
(复习一门语言,以question为主线,依次回答一下的一些最基本的问题(设计基本工具、语法形式、组织框架、交互式I/O、file I/O:
1,主要的开发工具是什么,是怎么样的,--交互式interpreter或者编写VIM以.py为extension的文件
2,程序代码的基本样子是怎么样的? --可以通过看一个基本的source code来有一个直观的印象。Python indention相关的non-free format的编码形式,不需要先声明后使用变量
3,基本的数据类型有那些? ---String, int list [] tuple (), dict { Key1 : Value1, Key2 : Value2} set ([a, b]))
CH1:
>>Python is one of those rare languages which can claim to be both simple and powerful. You will find yourself pleasantly surprised to see how easy it is to concentrate on the solution to the problem rather than the syntax and structure of the language you are programming in.
>>Interpreted: Internally, Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your computer and then runs it. All this, actually, makes using Python much easier since you don’t have to worry about compiling the program, making sure that the proper libraries are linked and loaded, etc. This also makes your Python programs much more portable, since you can just copy your Python program onto another computer and it just works!
>> OOP : In procedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object-oriented languages, the program is built around objects which combine data and functionality. Python has a very powerful but simplistic way of doing OOP,
>>Extensive and Embeded: 可以和C/C++良好的交互,方便的和这些更加big的语言建立接口。
>>当然也不会缺乏大量功能完备的library,而且大多基本的相关功能library都已经被包含在standard library之中了。BATTERIES——INCLUDED Batteries Included philosophy of Python.)
CH3:INSTALLATION
CH4:HELLO WORLD
CH5:Basics:
>> comments:Comments are any text to the right of the # symbol and is mainly useful as notes for the reader of the program. #Code tells you how, comments should tell you why
>>Literal Constants
>>Numbers: 52.3E-4 means 52.3 * 10-4. int类型可以表示任意长度的整数,no need to missing long.
>> Strings:有三种选择,‘’、“”、''' '''、""" """. This means that once you have created a string, you cannot change it.
"{0} {1}".format(a,b)
>> To prevent this newline character from being printed, you can end the statement with a comma: print "a",
>> in a string, a single backslash at the end of the line indicates that the string is continued in the next line, but no newline is added.
"This is the first sentence. \
This is the second sentence."
is equivalent to
"This is the first sentence. This is the second sentence."
>>raw string : r"nihao"
>>Python is strongly object-oriented in the sense that everything is an object including numbers, strings and functions.
>>Logical And Physical Line
A physical line is what you see when you write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line.(书写相关的)
>> Implicitly, Python encourages the use of a single statement per line which makes code more readable.
>> if you have a long line of code, you can break it into multiple physical lines by using the backslash. This is referred to as explicit line joining:
print \
i
等价与 print i
>>Python是indentation相关的,这已经是熟为人知的了。whitespace at the beginning of the line is important.
Ch6: operator and expressions
>> ^ :(bit-wise XOR) ** :指数运算 ~ : (bit-wise invert) boolean not and or
Ch 7 control flow
>> if: -elif:-else: , while:else:, for in :, 注意在block内的缩减!
>>no switch statement in Python.
>>The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence.
>>break and continue
ch 8 Functions
>>Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed by a pair of parentheses which may enclose some names of variables, and by the final colon that ends the line. Next follows the block of statements that are part of this function.
>>尽量少用global
>> 默认参数 def say(message, times=1): Only those parameters which are at the end of the parameter list can be given default argument values
>>Keyword Arguments we use the name (keyword) instead of the position (which we have been using all along) to specify the arguments to the function.
>>VarArgs parameters can take any number of parameters,
eg:
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
print total(10, 1, 2, 3, vegetables=50, fruits=100)
(输出为166)
When we declare a starred parameter such as *param , then all the positional arguments from that point till the end are collected as a tuple called param. Similarly, when we declare a double-starred parameter such as **param , then all
the keyword arguments from that point till the end are collected as a dictionary called param.
>>The pass statement is used in Python to indicate an empty block of statements.
>>DocStrings(增强可读性)
DocStrings are an important tool that you should make use of since it helps to document the program better and makes it easier to understand.A string on the first logical line of a function is the docstring for that function. Note that DocStrings also apply to modules and classes
The convention followed for a docstring is a multi-line string where the first line starts with a capital letter and ends with a dot. Then the second line is blank followed by any detailed explanation starting from the third line. You are strongly advised to follow this convention for all your docstrings for all your non-trivial functions.
strongly recommend that you use docstrings for any non-trivial function that you write.
Ch9 modules
>>Modules: Python的代码组织形式要比C++简单许多,只需要把我们定义的需要重用的function、class等正常的放到一个XX.py文件中,然后子啊同一目录下(或者其他sys.path可以得到的环境路径下)就可以为我所用,在需要使用时,在该.py的首部加 import XX(文件名)就可以了,在该文件中调用函数就可以直接使用XX.yy 使用class对象同样可以采用XX.ccc(parameters)来构造。(every Python program is also a module. You just have to make sure it has a .py extension. )
If it was not a compiled module i.e. a module written in Python, then the Python interpreter will search for it in the directories listed in its sys.path variable. If the module is found, then the statements in the body of that module are run and the module is made available for you to use. Note that the initialization is done only the first time that we import a module.
>> modules之__name__ : Every module has a name and statements in a module can find out the name of their module. This is handy for the particular purpose of figuring out whether the module is being run standalone or being imported.
>>NEVER : Remember that you should avoid using import-star, i.e. from mymodule import * .
>>对于更加复杂的层次性的组织方法,我们可以使用 Packages,Packages are just folders of modules with a special __init__.py file that indicates to Python that this folder is special because it contains Python modules.即在每一层的目录中都附件一个名为__init__.py的文件(可以为空)即可。
Ch10 DATA Structure
>>List [,,,,,] : mutable 如sort()就是完成inplace的自我排序
>>Tuple (,,,,,) :immutable,内容不可更改 ,注意,即使Tuple中定义时只有一个元素时,也要后附一个“,” (a,)以免和函数的语法形式冲突。
>>Dict { : , : , : } we associate keys (name) with values (details). Note that the key must be unique . use only immutable objects (like strings) for the keys of a dictionary but you can use either immutable or mutable objects for the values of the dictionary. .items()
>>以上三种都属于序列型的结构,可以进行indexing【】的访问,同时支持sciling(如【1:6:2】)的访问方式。
>>set ([,,,])Sets are unordered collections of simple objects. These are used when the existence of an object in a collection is more important than the order or how many times it occurs.
>>实际解决问题的建议:A recommended way of writing programs is the procedure we have followed in creating
the backup script: Do the analysis and design. Start implementing with a simple version. Test and debug it.
“Software is grown, not built.”
CH12 OOP
>>相对于C++ 也是简单了许多,构造函数由__init__(self,...)代替等@classmethod等的使用都使得定义class变得很简单。
Ch13 IO
IO就更简单了,
Interactive: aa = raw_input('..')
FILE:直接使用一般的三部曲 open write/readline close就可以基本解决了,完全不需要许多刻板的操作。
甚至于集体的object都可以通过inport pickle之后,通过dump()和load()进行存储!
而解决中文等unicode编码问题也非常的简单只需要指明u在代码最前加入#encoding=utf-8等最基本的设置就可以!
Exception
>>容错处理同样奉行极简注意,try: except: (和finally:)以及raise就足够了!
可见我非常喜欢Python,不仅是它的外表,它的功能,还有它的ZEN,十分的先进!和我的思想相近。所以确实是
可爱的Python!我已经爱上了她。接下来就是一定要完全的了解她!使用她!欣赏她!
关于@decorator:
The Python language provides a simple yet powerful syntax called ‘decorators’. A decorator is a function or a class that wraps (or decorates) a function or a method. The ‘decorated’ function or method will replace the original ‘undecorated’ function or method.
Decorator Introduction
(http://toumorokoshi.github.io/dry-principles-through-python-decorators.html)
If you're not familiar with decorators, they are effectively function wrappers that are run when the python interpreter loads the function, and can modify what the function receives and returns. For example, if I wanted to always return an integer result of one larger than whatever was returned, I could write my decorator as so:
# a decorator receives the method it's wrapping as a variable 'f'
def increment(f):
# we use arbitrary args and keywords to
# ensure we grab all the input arguments.
def wrapped_f(*args, **kw):
# note we call f against the variables passed into the wrapper,
# and cast the result to an int and increment .
return int(f(*args, **kw)) + 1
return wrapped_f # the wrapped function gets returned.
And now we can use it to decorate another method using the '@' symbol:
@increment
def plus(a, b):
return a + b
result = plus(4, 6)
assert(result == 11, "We wrote our decorator wrong!")
Decorators modify the existing function, and assign the variable to whatever is returned by the decorator. In this case, 'plus' really refers to the result of increment(plus)
The Standard Library
After looking at class definitions, it's important to look at the default library, subsection by subsection. There is a lot to the installed library.
For most Python programmers, sections 1 to 6 will have been covered by the previous material. Sections 26 and on to the end, also, are less important.
Sections 7 to 25 of the library reference contain the centrally important modules. A familiarity with the list of topics is essential before tackling "real" projects. This is so important, we'll use this set of topics as the basis for our point-by-point commentary on the mind-map linked above.
format(1, '#010b')