您的位置:首页 > 编程语言 > Python开发

Python语法笔记

2010-11-23 16:36 176 查看
tnnd,总算开始正儿八经学习Python了。

1. Number

在Python里,下面的表达式不是integer division,fractions aren't lost when dividing integres

8/5 = 1.6

而在Java里上面的表达式就是integer division

在Python里,表示integer division得用下面的表达式:

7//3 = 2 7//-3=-3

而且Python里整除的rounding方式也和Java不同,它是returns the floor,而在Java里是四舍五入

#Java code

7/3 = 2 7/-3=-2

Python里面不支持++,——运算。

2、多重赋值

Python里面赋值时先把右边都算出后再进行赋值

>>> def fib(n):

... a, b = 0, 1

... while a < n:

... print(a, end=' ')

... a, b = b, a+b

... print()

...

>>> # Now call the function we just defined:

... fib(2000)

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

所以上述函数才会打印出Fibonacci数列

3、global variable

all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

一个global variable可以被方法读,但是如果直接给它赋值的话,其实是创建了一个本地变量。除非加上global语句。

>>>a = 7

>>> def setA(value):

global a

a = value

print ("Inside setA, a is now %d" % a)

这样a的值才会改变

python里面有symbol table的概念

4、数据结构

List

>>> vec
= [2, 4, 6]

Tuples and Sequences

>>> t = 12345, 54321, 'hello!'

>>> t = (12345, 54321, 'hello!')

Sets

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> a = set('abracadabra')

Dictionaries

>>> tel = {'jack': 4098, 'sape': 4139}

>>> tel['guido'] = 4127

>>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098}

5、Module和package

Python里module被定义为一个以.py结尾的文件,类似于Java里的.class文件。你可以通过import的方式将其引用进来:

当在代码中有import语句时,系统去哪里查找这个文件呢?

顺序如下:sys.path(在IDLE里File菜单下的Path Browser) -> PYTHONPATH -> installation-dependent default

当文件一多,肯定需要将它们放在不同的目录下便于管理,所以这时候需要用到package,它对应的其实是目录,但是一个目录想要成为package,必须在其根目录下存在一个__init__.py文件(内容是空的也必须有这么个文件,当然可以在里面做一些配置),除了这点和Java里的package没太多不同

6、Namespace and Scope

A namespace is a mapping from names to objects.

A scope is a textual region of a Python program where a namespace is directly accessible. "Directly accessible" here means that an unqualified reference to a name attempts to find the name in the namespace.

Although scopes are determined statically, they are used dynamically. At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:

the innermost scope, which is searched first, contains the local names

the scopes of any enclosing functions, which are searched starting whith the nearest enclosing scope, contains non-local, but also non-global names

the next-to-last scope contains the current module's global names

the outermost scope (searched last) is the namespace containing built-in names

7. Class Objects, Instance Objects, Method Objects

Python里面class和instance的应用比Java灵活得多,Class objects和instance objects都支持attribute references

Class Objects:attribute references and instantiation

class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'


MyClass.i -> 12345

MyClass.f -> <function f at 0x00FCC1E0>

MyClass.f("abc") -> 'hello world' (必须得带一个参数,否则会出错)

x = MyClass()

Instance Objects attribute references: data attributes and methods

x.i -> 12345

x.f -> <bound method MyClass.f of <__main__.MyClass object at 0x00FDC330>>

(注意x.f和MyClass.f的区别,前者是method object,而后者是function object)

x.f() -> 'hello world'

x.f("abc") -> 出错,因为这个时候x作为隐含的第一个参数,相当于MyClass.f(x)

而Instance Objects一个比较奇怪的特性就是,你可以给它设置任何data attributes值,比如:

x.name = "Mike"

x.salary = 10000

8. Testing

Python里的doctest特别有意思,the doctest module provides a tool for scanning a module and validating tests embedded in a program's docstrings. 这样注释里的例子就可以作为test case了。

9. Data Type

Python里包括三大类数值:integers, floating point numbers, and complext numbers,没Java里面分得那么细

Integers:Integers(int) and Booleans(bool)

注意:python里int是没有大小限制的,仅仅受限于可用的(虚拟)内存

->: subclass of

bool ->int -> Integral -> Rational -> Real -> Complex -> Number

10. metaclass

In short: A class is a blueprint for the creation of an instance, a metaclass is a blueprint for the creation of a class. It can be easily seen that in Python classes need to be first-class objects too to enable this behavior.

用途:A metaclass is most commonly used as a class-factory, 可以用来完成一些AOP编程。一般很少用到,一个典型的例子就是ABCMeta in abc.py,然后Number使用了该metaclass,默认所有类的metaclass都是type

SO有一个问题专门讲这个的:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python

11. decorator

A function returning another function, usually applied as a function transformation using the @wrapper syntax.

下面是个简单的例子

def require_int(funcobj):
def re(arg):
if type(arg) == int:
return funcobj(arg)
else:
raise ValueError("the arg must be an int")
return re
@require_int
def get_int(x):
return "I got the %s" % x
print(get_int(0))
print(get_int(20))
get_int('abc')


还有比较常用的decorator还有classmethod(), staticmethod(), abstractmethod()等。

12、闭包(Closure)

例子:

def addx(x):
def adder (y): return x + y
return adder
add8 = addx(8)
add9 = addx(9)
print add8(100)
print add9(100)


或使用lambda关键字:

def addx(x):
return lambda y: x + y
add8 = addx(8)
add9 = addx(9)
print add8(100)
print add9(100)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: