1.开头设置编码

#coding=utf-8

各国的编码规范混在一起,容易出现乱码的现象。Unicode标准统一了编码,但较浪费空间,因而出现了“可变长编码”的utf-8

  • 计算机系统通用的字符编码工作方式:
    文本存取
    浏览网页
1
2
3
4
5
6
7
#获取字符的整数表示值
print(ord('A'))
#获取对应字符
print(chr(66))
#对str,len()函数计算字符数,对bytes,len()函数计算字节数
len('中文') #2
len('中文'.encode('utf-8')) #6

2.声明变量 不用声明类型

a=10
b=5

3. 条件语句

1
2
3
4
5
6
7
8
score = 90
if score<80 :
#print前面必须要有缩进
print("优秀")
elif score>60 :
print("及格")
else :
print("不及格")

4.循环语句

1
2
3
4
for i in range(1,100,4):
#python特有的字符串拼接方式
print("数字{0},{1}".format(i,"hello python"))
print('%s,现在的数字是%d' % ('python',i))

5.数据类型list和元组,字典dict和key集合set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fruits = ['apple', 'peal', 'orange']#中间逗号后需有空格
#python可倒叙遍历
print(fruits[-1]) #orange
fruits.append('banana')
fruits.insert(2, 'watermelon')
#删除list末尾的元素
fruits.pop()
#list元素也可以是另一个list
s = ['python', 'java', ['asp', 'php'], 'scheme']
len(s) #4
#元组
classmates = ('Michael', 'Bob', 'Tracy')
#dict,拥有较快查找速度,占空间大
#要保证hash的正确性,作为key的对象就不能变。在Python中,字符串、整数等都是不可变的,因此,可以放心地作为key。而list是可变的,就不能作为key
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
d['Adam'] = 67
#set中key不能重复,不存储value

6.函数定义

1
2
3
4
5
def max(a,b):
if a>b:print(a)
else:print(b)
max(3,5)

7.高级特性

  • 切片 -- 简化list截取操作
1
2
3
4
5
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
#截取从0到3的list(不包括3)
M = L[0:3] #['Michael', 'Sarah', 'Tracy']
#字符串也可使用切片
s = 'ABCDEFG'[::2] #'ACEG'
  • 迭代
1
2
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)
  • 函数式编程

    • map/reduce

      1
      2
      3
      4
      5
      6
      7
      8
      def f(x):
      return x * x
      #map(f,Iterator)
      r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
      list(r) #[1, 4, 9, 16, 25, 36, 49, 64, 81]
      list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))#['1', '2', '3', '4', '5', '6', '7', '8', '9']
      #reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
    • filter

      1
      2
      3
      4
      5
      6
      #filter()把传入的函数依次作用于每个元素
      def not_empty(s):
      return s and s.strip()
      list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
      # 结果: ['A', 'B', 'C']
    • sorted 排序函数

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      sorted([36, 5, -12, 9, -21], key=abs) #key定义排序方式,此处为按绝对值大小,[5, 9, -12, -21, 36]
      sorted(['bob', 'about', 'Zoo', 'Credit']) #['Credit', 'Zoo', 'about', 'bob'],默认按照ASCII的大小顺序排列
      sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) #['Zoo', 'Credit', 'bob', 'about']
      ```
      - 返回函数和闭包
      ```python
      def calc_sum(*args):
      def sum():
      ax=0
      for n in args:
      ax = ax + n
      return ax
      return sum
      f = calc_sum(1, 3, 5, 7, 9) #返回sum函数,且该函数并未执行
      f()
    • 匿名函数

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      f = lambda x: x * x #关键字lambda表示匿名函数
      f(5)
      #也可以把匿名函数作为返回值返回
      def build(x, y):
      return lambda: x * x + y * y
      ```
      #### 8.面向对象 支持多重继承(实际与java的接口类类似)
      ```python
      class Animal:
      def __init__(self,name):
      self._name=name
      def say(self):
      print("发出声音")
      #实例的变量以`__`开头则表示一个私有变量,外部不能访问,如 __name
      #Cat类继承自Animal
      class Cat(Animal):
      #覆写父类的构造方法
      def __int__(self,name):
      Animal.__init__(self,name)
      def say(self):
      print("{0}---喵~~".format(self._name))
      cat = Cat("Cancy")
      cat.say()
  • 可以给实例绑定一个方法,但给一个实例绑定的方法对另一个实例是没作用的

  • 使用slots来限制可以绑定的属性
  • type()函数可以查看一个类型或变量的类型,可以创建出新的类型

    1
    2
    class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
  • Python内置的@property装饰器负责把一个方法变成属性调用的,可用以防止属性被随意修改

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    def fn(self, name='world'): # 先定义函数
    print('Hello, %s.' % name)
    Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class
    #要创建一个class对象,type()函数依次传入3个参数:
    #1.class的名称;
    #2.继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
    #3.class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。

9.引入py文件

1
2
3
4
5
6
7
8
9
import mylib
h = mylib.hello()
h.sayHello()
from mylib import Hello
h = Hello()
h.sayHello()

10.I/O操作

读写文件
1
2
3
4
5
6
7
8
9
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
#Python引入了with语句来自动帮我们调用close()方法,上面可改为:
with open('/path/to/file', 'r') as f:
print(f.read())
StringIO(在内存中读写str), BytesIO(在内存中读写bytes)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#StringIO
from io import StringIO
f = StringIO()
#写
f.write('hello')
#读
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
#BytesIO
from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))


学习中…