关于python:Python-笔记

3次阅读

共计 17546 个字符,预计需要花费 44 分钟才能阅读完成。

Python

简介

Python 由 Guido van Rossum(荷兰 🇳🇱)开发。

Python 是一门解释型语言、动静类型(弱类型)语言。

Python 的名字来源于 Monty Python’s Flying Circus。

保留词

不能应用保留词(reserved words)来命名变量名称,这样的词有:

False, class, return, is, finally, None, if, for, lambda, continue, True, def, from, while, nonlocal, and, del, global, not, with, as, elif, try, or, yield, assert, else, import, pass, break, in, raise

Python 的关键字很靠近自然语言:

  • True,False 布尔值,相当于“真,假”,相似于其余语言中的 true, false
  • None 相当与“空”,相似于其它语言中的 null
  • is,is not 运算符用于逻辑表达式,前者的意思是“和什么雷同”,类似于 ==,然而更强。is 同时查看值和类型,罕用在 None 或者布尔值的判断,相似 JavaScript 中的 ===
0 == 0.0 # True
0 is 0.0 # False

构建块

赋值

赋值就是把变量名和数值分割起来,定义函数就是把函数名和表达式分割起来。

赋值运算符 =

常量

Python 中能够间接应用常量。

print(322)
print(5.3)
print("Hello World")

变量

Python 中的变量不须要用关键字申明,能够间接赋值。

x = 12.2    
y = 14      
变量命名规定
  • 必须以字母或下划线 _ 结尾
  • 必须由字母、数字和下划线组成
  • Python 辨别大小写

语句

x = 2 # 赋值语句
x = x + 2 # 赋值表达式
print(x) # print 语句

应用 = 把值赋值给某一个变量。赋值运算符是从右开始计算的。

环境图

环境图用于显示变量和其数值之间的对应关系。

表达式

表达式形容了一次计算和取值。

所有的表达式都能够通过函数表达式实现。

例如:max(1,2) 这样的称为调用表达式(call expression),它的构造如下:

add        (2    ,     3)
operator  operand operand

操作符和操作数也是表达式。

数字表达式

应用 +, -, *, /, **, % 做数学运算,其中 ** 是幂运算。

print(4 ** 3) # 64

运算符的优先级

  • 括号最高 ()
  • 幂运算 **
  • 乘法、除法、求余 * / %
  • 加法、减法 + -
  • 从左到右 from left to right

逻辑运算符

  • not 为非运算符,相似其余语言的 !
  • and 为与运算符,相似其余语言的 &&
  • or 为或运算符,相似其它语言的 ||

三元运算符

Python 中的三元运算符和其余编程语言不同: condition ? x : y,而是 result = x if condition else y

类型

Python 的变量、常量、字面量都有类型。

有些运算是禁止的,例如:1 + string。

能够应用 type() 找出某个数据的类型。

Python 中有隐式类型转换。

type(1)
# <class'int'>

数字

次要有 int, float, double 类型。

Python 中整数的除法后果是浮点数。

字符串转化

能够应用 int(),float(),能够把字符串变成整数。如果字符串中不蕴含数字,那么会失去 error

字符串

Python 能够应用单引号 '' 或者双引号 "" 来示意字符串。

字符串蕴含数字,依然是字符串。

字符串是不可变的(immutable)。例如:

s = "hello"
s[0] = 'y' # error
s = 'y' + s[1:len(s)] # 能够,因为 s 当初是一个新对象
s = "yello" # 能够

字符数字转换

能够应用 int() 把字符串转化为数字。

能够应用 str() 把数字转化为字符串。

通常应用字符串来接管输出,而后再转化为想要的类型。

Python 3 中所有的字符串编码都是 Unicode。

字符串索引

能够应用 [] 来获取字符串中某个地位的字符。索引从 0 开始。

在 Python 中能够应用 负值 作为索引,最初一个元素的索引为 -1,随着负值的减小,也就是绝对值的增大,实际上相当于从右往左拜访字符串。

fruit = 'app'
letter = fruit[0]
print(letter) # a
print(fruit[9]) # error
print(fruit[-1]) # p

字符串长度

应用 len() 取得字符串的长度。

fruit = 'banana'
x = len(fruit)
print(x) # 6

字符串循环

上面两段代码是一样的成果,第二种更 Python。

s = "abcdef"
for index in range(len(s)):
  if s[index] == 'i' or s[index] == 'u':
    print("there is i or u")
    
    
for char in s:
  if char == 'i' or char == 'u':
    print("there is i or u")

能够应用 for 或 while 循环。

fruit = 'banana'
index = 0
while index < len(fruit):
  letter = fruit(index)
  print(letter)
  index = index + 1
  
  
for letter in fruit:
  print(letter)

字符串切片

应用 : 运算符(colon operator)实现字符串的切片操作。

切片运算符 [start:stop:step]

第一个数字是切片的开始地位,第二个数字是指切片的完结地位(直到但不蕴含该地位),第三个数字代表步长(默认为 1)。

如果省略第一或第二个数字,只留下冒号,那么默认从头或到尾。

s = 'Monty Python'
print(s[0:4]) # Mont
print(s[8:]) # thon
print(s[:2]) # Mo
print(s[:]) # Monty Python

s = "abcdefgh"
s[3:6] # "def" 和 s[3:6:1] 雷同
s[3:6:2] # "df"
s[::] # "abcdefgh" 和 s[0:len(s):1] 雷同
s[::-1] # "hgfedbca" 和 s[-1:-(len(s)+1):-1] 雷同,相当于反转字符串
s[4:1:-1] # "ec"

字符串拼接

应用 + 连贯(concatenate)字符串。

hello = "hello"
world = "world"
print(hello + world)
# helloworld

检测子串

应用 in 作为逻辑运算符。能够检测一个字符串是否被蕴含在另一个字符串中,返回一个布尔值。

fruit = 'banana'
'n' in fruit # True
'm' in fruit # False

字符串比拟

应用比拟运算符比拟字符串。

if word == 'banana':
  print("all right")

if word < 'banana':
  print('your word' + word + ', coes before banana')

字符串反复

应用 * 运算符来对字符串反复。

silly = "hello" * 3
print(silly)
# hellohellohello

字符串库

应用字符串库中的函数,这些函数不会扭转本来的字符串,而是返回一个新字符串。

应用 type() 查看字符串类型,相似 JavaScript 的 typeofdir() 能够查看可能用在字符串上的所有办法。

s = ""
type(s)
>>> <type 'str'>

应用 find() 查找字符串的子串,它查找子串第一次呈现的地位,如果没有找到返回 -1,相似 JavaScript 的 indexOf()

fruit = 'banana'
pos = fruit.find('na')
print(pos) # 2

应用 lower(), upper() 把字符串转化为小写或者大写,相似 JavaScript 的 toUpperCase(), toLowerCase()

great = 'Hello World'
zap = great.lower()
print(zap) # hello world

应用 replace() 意思是查找并替换,它会替换所有查找到的子串。

great = 'hello bob'
nstr = great.replace('bob', 'jane')
print(nstr) # hello jane
nstr = great.replace('o', 'x')
print(nstr) # hellx bxb

应用 lstrip()rstrip() 来移除右边或者左边的空白,strip() 移除所有空白。

greet = 'hello bob'
greet.lstrip() # 'hello bob'
greet.rstrip() # 'hello bob'
greet.strip() # 'hello bob'

应用 startswith() 来判断字符串前缀。

line = 'please have a nice day'
line.startswith('please') # True

split() 办法把一个字符串宰割成一个字符串列表。

如果没有指定宰割符,默认采纳空格作为分隔符。

abc = 'with three words'
stuff = abc.split()
print(stuff)
['with', 'three', 'words']
print(len(stuff))
# 3
line = 'first:second:third'
thing = line.split()
print(thing)
# ['first:second:third']
print(len(thing))
# 1
thing = line.split(":")
print(thing)
# ['first','second','third']

两次切片

words = 'His e-mail is q-lar@freecodecamp.org'
pieces = words.split()
parts = pieces[3].split('-')
n = parts[1]
# lar@freecodecamp.org

输入输出

输出

应用 input() 取得用户输出,该函数返回一个字符串。

name = input('Who are you')
print('welcome', name)
输出的转化

如果想读一个数字,那么必须把获取的字符串转化为数字。

inp = input('Europe floor')
usf = int(inp)
# usf = float(inp)
print('US floor', usf)

输入

应用 print() 输入。应用 , 能够在值两头增加空格。如果应用 + 须要保障两端都是字符串。

x = 1
print(x)
x_str = str(x)
print(x)
print("my fav num is", x, ".", "x =", x)
print("my fav num is" + x_str + "." + "x =" + x_str)

正文

Python 应用 # 来正文单行语句。

应用 '''''' 正文多行语句。

# 正文

'''正文'''

Python 脚本

Python 的文件以 .py 结尾。

运行 Python 文件应用命令:

python file.py

缩进

  • 缩进(indentation)呈现在 if 语句或者 for 语句等之后的 :
  • 应用缩进来批示作用域
  • iffor 语句完结时要把缩进返回到上一级
  • 空行会被疏忽,它们不会影响缩进
  • 正文同样会被疏忽

注:Python 查看缩进的正确性,所以不要弄混 spacetab

条件

x = 5
if x < 10:
  print("smaller")
if x > 20:
  print("bigger")
print("Finis")

比拟运算符

比拟运算符:<, <=, ==, >=, >, !=

比拟运算符罕用在布尔表达式中,返回真或假。

比拟运算符不会扭转变量的值。

if else

x = 4
if x > 2:
  print("bigger")
else:
  print("smaller")
print 'all done'

if elif else

if x < 2:
  print("small")
elif x < 10:
  print("meduim")
else:
  print("large")
print("all done")

为“True”的条件

a = True

if a is True:
  print("True")
  
if a == True:
  print("True")
  
if a:
  print("True")
  
if bool(a):
  print("True")
  
# 以上四种后果皆为 True  

以上四种判断的相同点:

  • 后果均为 True

不同点:

  • 第一种是判断 a 是否为 True,如果是 True 之外的任何一个值,都不会通过条件判断。

    这种做法适宜于把 True 独自拿进去作为一种状况。

    a is True 的背面不是 a is False,而是 a is not True。

  • 第二种实际上不太应该呈现。

    == 运算符在 Python 中会被重载,所以判断是不是 True 自己,应该用第一种做法。

  • 第三种适宜于十分确定 a 的类型的状况。
  • 第四种中 bool 是一个 Class,这种写法和第三种没有什么区别。

循环

while

n = 5
while n > 0:
  print(n)
  n = n - 1
print("blasoff")

应用 break 语句能够完结并跳出以后循环。

while True:
  line = input('>')
  if line == 'done':
    break
  print(line)
print('done')

应用 break 语句能够完结以后循环并回到循环顶部。

while True:
  line = input('>')
  if line[0] == '#':
    continue
  if line == 'done':
    break
  print(line)
print('done!')  

for

for range

有些循环的次数是确定的:

for n in range(5):
  print(n)
  # 0 1 2 3 4

留神从 0 开始,而后到 range 内的值减 1。

range 函数签名:range(start, stop, step),其中 start 代表迭代开始的数字,stop 代表完结的数字 + 1,step 代表迭代的步长。参数必须是整数。如果是倒序循环,步长为 -1

for i in range(1,4):
  print(i)
# 1,2,3

for i in range(1,4,2):
  print(i)
# 1,3
for in

例如 for in 循环能够迭代汇合全副元素,相似 JavaScript 的 forEach()

for i in [1,2,3,4,5]:
  print(i)
print('blase off')
# 1,2,3,4,5

friends = ['tom','cat']
for friend in friends:
  print('happy:', friend)
print('done')
# happy: tom
# happy: cat
# done

下面例子中的:ifriend 被称为迭代变量,用来迭代列表。每次只会执行一次。

更“聪慧”的循环:

找出列表中的最大数字:

largest_so_far = -1
print("before", largest_so_far)
for the_num in [1,2,3,45,6]:
  if the_num > largest_so_far:
    largest_so_far = the_num
  print(largest_so_far, the_num)
  
print('after', largest_so_far) # 74

计数循环:

zork = 0
print('before', zork)
for thing in [1,2,3,4,5]:
  zork = zork + 1
  print(zork, thing)
print('after', zork)

计算总和:

zork = 0
print('before', zork)
for thing in [1,2,3,4,5]:
  zork = zork + thing
  print(zork, thing)
print('after', zork)

平均数:

count = 0
sum = 0
for value in [1,2,3,4,5]:
  count = count + 1
  sum = sum + value
print('average', sum / count)

应用布尔值查找变量:

found = False
for value in [1,2,3,4,5]:
  if value == 3:
    found = True
print(found)

函数

定义

函数是保留并重复使用的代码段,它接管参数,做运算,并返回后果。

直到程序调用(called)或者援用(invoked)函数才会运行。

特点

  • 有函数名
  • 有参数(0 或多个)
  • 有正文(docstring)(可选然而举荐)
  • 有函数体
  • 有返回值

编写和调用

应用 def 关键字去定义函数。

通过函数名来调用函数。

Python 中有两种函数:

  1. 内置函数是 Python 语言提供的
  2. 自定义的函数

return 语句会完结函数执行,并返回函数的后果。

如果没有指定 return 语句,Python 会返回 None

实参(actual parameter),形参(formal parameter),参数能够是函数类型的。

函数签名指明了函数承受参数的个数,函数签名含有所有发明部分作用域的信息。

def <name>(<formal parameters>):
  return <return expression>
def fun_a():
  print("this is a")

print fun_a() # None

上面是一个例子:

def is_even(i):
  """
  Input: i, a positive int
  Returns True if i is even, otherwise False
  """print("inside is_even")
  return i % 2 == 0

is_even(3)
def thing():
  print('hello')
  print('fun')
thing()
print('zip')
thing()

def great(lang):
  if lang == 'es':
    print('hola')
  elif lang == 'fr':
    print('bonjour')
  else:
    print('hello')

作用域

有全局作用域和部分作用域两种。

  • 在函数外部,能够拜访内部定义的变量
  • 在函数外部,不能扭转内部定义的变量 — 能够应用全局变量
# example1
def f(y):
  x = 1
  x += 1
  print(x)
  
x = 5
f(x)
print(x)

# example2
def g(y):
  print(x)
  print(x + 1)

x = 5
g(5)
print(x)

# example3
def h(y):
  x += 1
  
x = 5
h(x)
print(x)
# unboundLocalError

列表

定义

列表是一种汇合。有许多值存在一个变量中。

friends = ['wu', 'niu', 'su']

列表常量是指用户用方括号 [] 突围的一组元素,元素之间用逗号宰割。

列表的元素能够是任何 Python 对象,甚至是另一个列表(狭义表)。

列表能够为空。

l = []
c = ['code', 42]
a = [3, [2,1], 3]

拜访

能够应用方括号实现索引拜访列表。

code = ['code','apple']
print(code[0]) # code

列表是可变的(mutable),能够应用索引操作符批改列表元素,依然是一个对象。字符串是不可变的,必须在一个新的字符串上做批改。

c = ['code', 42]
c[0] = 1
print(c) # [1, 42]

迭代

列表能够被迭代,上面是两种罕用的模式。

注:

  • 索引从 0len(l) - 1
  • range(n) 从 0n-1
# example1
total = 0
for i in range(len(l)):
  total += l[i]
print total

# example2
total = 0
for i in l:
  total += i
print total

拼接

应用 + 拼接列表,原来的列表不会被扭转。

a = [1,2,3]
b = [4,5,6]
c = a + b
print(c) #[1,2,3,4,5,6]

切片

应用 : 对列表做切片。

t = [1,2,3,4,5]
t[1:4] #2,3,4

type() & dir()

应用 type() 查看列表类型,dir() 能够查看可能用在列表上的所有办法。

<type 'list'>

增加

应用 append() 办法增加元素到列表开端。

stuff = list()
stuff.append('book')
stuff.append('cookie')

删除

应用 del(L[index]) 能够删除一个给定索引的元素。

应用 pop() 删除列表的开端元素,并返回被删除的元素。

应用 L.remove(element) 删除一个给定元素。

  • 先找到元素并删除
  • 如果该元素呈现了屡次,只删除第一个
  • 如果列表没有该元素,给出谬误
L = [2,1,3]
L.remove(2) # L = [1,3]
del(L[0]) # L = [3]
L.pop() # return 3 && L = []

in & not in

应用 in, not in 判断某元素是否在一个列表,返回一个布尔值。

t = [1,2,3,4,5]
1 in t 
# True
8 not in t
# True

排序、反转

应用 sort()sorted() 对列表排序。

sorted() 不会扭转原列表,返回一个排序列表。

sort() 排序原列表。

reverse() 反转列表。

t = [1,3,2,4,5]
t.sort() # t = [1,2,3,4,5]
t.sorted() # return [1,2,3,4,5] t = [1,3,2,4,5]
t.reverse() # t = [5,4,2,3,1]

len(),max(),min(),sum()

len(),max(),min(),sum()等办法把列表作为参数。

列表字符串互转

应用 list(s) 把字符串转化为列表,返回一个列表带有字符串中的每个字符。

应用 s.split() 宰割一个字符串依据指定参数,如果没有参数则以空格宰割。

应用 `.join(L)` 把字符列表转化字符串。引号里的内容是每个元素间的分隔符。

s = "I<3 cs"
list(s) # ['I', '<', '3', '','c','s']
s.split('<') # ['I', '3 cs']

L = ['a','b','c']
''.join(L) #"abc"'_'.join(L) #a_b_c

克隆

应用 [:] 克隆一个列表(创立一个新列表,并拷贝所有元素)

cool = ['blue']
chill = cool[:]
chill.append('black')
print(chill) # ['blue','black'] 
print(cool) # ['blue']

字典

定义

字典(dictionary)是多个值的“背包”,每个值都有一个标签,相似于键值对,哈希表数据结构,JavaScript 对象,Java 属性或者 Map 或 HashMap。

字典字面量(常量)应用花括号 {} 来示意一个键值对组。也能够应用花括号来创立空字典。

字典的值能够是任何类型,然而键必须是惟一的,而且必须是不可变的,也就是 float、tuple、int、string、boolean。

jjj = {'chuck': 1, 'fred': 43, 'jan': 100}
print(jjj)
# {'chuck': 1, 'fred': 43, 'jan': 100}
ooo = {}
print(ooo)
# {}

拜访

字典是无序的,所以不能用地位也就是数字索引拜访,须要标签,也就是字符索引。

purse = dict()
purse['money'] = 12
purse['candy'] = 12
print(purse)
# ['money': 12, 'candy': 12]
purse['candy'] = purse['candy'] + 2
print(purse)
# ['money': 12, 'candy': 14]

如果拜访一个不存在的键,Python 会给 error。

增加删除

应用 [] = 来增加一个键值对。

grades['Sylvan'] = 'A'

应用 del() 删除一个键值对。

del(grades['Ana'])

in

能够应用 in 操作符拜访键是否在字典中。

ccc = dict()
print(ccc['csev'])
# Traceback ...
'csev' in ccc 
# False

如果发现了一个新名字,退出字典,随后再发现,就叠加字典的值

counts = dict()
names = ['csev','cwen']
for name in names:
  if name not in counts:
    counts[name] = 1
  else:
    counts[name] = counts[name] + 1 
print(counts)    

get

get() 办法查看字典中是否曾经存在一个键,如果不存在会给该键设定一个默认值。

if name in counts:
  x = counts[name]
else:
  x = 0

# 下面 4 行和上面 1 行雷同

x = counts.get(name, 0)  

计算文本中每行的字数须要宰割行为单词,而后循环单词列表,并用字典去跟踪每个单词。

counts = dict()
print('enter a line of text:')
line = input('')

words = line.split()

print("words:"+ words)

print("counting...")
for word in words:
  counts[word] = counts.get(word,0) + 1
print('counts', counts)

只管字典是无序的,然而依然能够应用 for 循环去迭代字典的键。

counts = {'chuck': 1, 'fred': 43, 'jan': 100}
for key in counts:
  print(key, counts[key])
  
# chuck 1
# fred 43
# jan 100

list()、.keys()、.items()

应用 list() 把字典的键转化为列表。

应用 .keys() 失去字典的键的列表, 应用 values() 失去字典值的列表,应用 .items() 失去字典键值对的元组。

jjj = {'chuck': 1, 'fred': 43, 'jan': 100}
print(list(jjj))
# ['chunk','fred','jan']
print(jjj.keys())
# ['chunk','fred','jan']
print(jjj.values())
# [1,43,100]
print(jjj.items())
# [('chuck', 1), ('fred', 43), ('jan', 100)]

双迭代变量,能够间接输入键值对。

jjj = {'chuck': 1, 'fred': 43, 'jan': 100}
for aaa,bbb in jjj.items():
  print(aaa, bbb)

# chuck 1
# fred 43
# jan 100

双重循环

bigcount = None
bigword = None
for word.count in counts.items():
  if bigcount is None or count > bigcount:
    bigword = word
    bigcount = count
print(bigword, bigcount)   

元组

定义

元组(tuple)相似于列表,索引也是从 0 开始。

元组能够蕴含整型、浮点型、字符串等。

应用括号(parentheses) () 来示意元组。

te = ()

t = (2, "mit", 3)

x = ('Glenn', 'Sally')
print(x[1])
# Sally

y = (1, 2, 3)
print(y[1])
# 2
print(max(y))
# 3

for item in y:
  print(item)
# 1
# 2
# 3

元组和列表的区别是,元组是不能扭转的(immutable),这相似于字符串。

元组中不能做的事

  • 元组对象不能被排序(sort())
  • 元组对象不能增加(append())
  • 元组对象不能被翻转(reverse())

元组只有 countindex 属性。

拼接元组

应用 + 能够拼接元组

(2, "mit", 3) + (5, 6)
# (2, "mit", 3, 5, 6)

元组切片

应用 [:] 能够对元组切片。

t[1:2] # ("mit",)
t[1:3] # ("mit", 3)

留神第一个例子的 , 不是谬误,而是 Python 示意这是一个元组,否则就变成了字符串。

元组大小

应用 len() 失去元组大小。

便捷的替换操作

(x, y) = (y, x)

赋值

能够把元组放在赋值运算符的左侧,甚至能够疏忽括号。

(x, y) = (4, 'fred')
print(y) # fred
(a, b) = (99, 98)
print(a) # 99

比拟

元组是能够比拟的。如果第一个元素雷同,会持续比拟。

(0, 1, 2) < (5, 1, 2)
# True
(0, 1, 20000) < (0, 3, 4)
# True

迭代

元组能够被迭代。

排序

能够应用 sorted() 对元组列表排序。

d = ['a': 10, 'b': 10, 'c': 10]
d.items()
sorted(d.items())

按值排序:

d = ['a': 10, 'b': 20, 'c': 30]
tmp = list()
for k,v in c.items():
  tmp.append((v, k))
print(tmp)
# [(10, 'a'), (30, 'c'), (20, 'b')]
tmp = sorted(tem, reverse=True)
print(tmp)
# # [(30, 'c'), (20, 'b'), (10, 'a')]

更短的版本:

print(sorted([(v, k) for k,v in c.items()]))

别名

所有的别名(alias)指向同一对象,所以对其中一个更改,其余的也会更改。

a = 1
b = a
print(a) # 1
print(b) # 1

warm = ['red', 'yellow', 'orange']
hot = warm
hot.append('pink')
print(hot) # ['red', 'yellow', 'orange', 'pink']
print(warm) # ['red', 'yellow', 'orange', 'pink']

断言

断言(assertion)用来判断预期和理论后果雷同。

def avg(grades):
  assert not len(grades) == 0, 'no grades data'
  return sum(grades)/len(grades)

如果是空列表,给出 AssertionError,其余状况 ok。

异样

try except

异样应用 try/except 构造。

  • 对于一段“危险”代码,应该应用异样解决
  • 如果 try 中的代码能够工作,那么 except 的局部会被跳过
  • 如果 try 中的代码不能工作,那么会跳转到 except 的局部
name = 'Bob'
try:
  print('hello')
  istr = int(name)
  print('there')
except:
  istr = -1
print('done', istr)  

应用多个 except 语句解决某种非凡状况的异样

try:
  ...
except ValueError:
  ...
except ZeroDivisionError:
    ...
except:
  ...

else & finally

else 在 try 中语句没问题时运行,finally 无论 try 中语句是否有谬误都会执行。

raise

当呈现谬误时,显示谬误条件。

在 Python 中,抛出一个 exception 应用 raise

格局:raise <exceptionName>(<arguments>)

raise Exception("descriptive string")

面向对象编程

class & object

class 是类的关键字,object 类是 Animal 的父类,__init__ 是创立实例的办法(留神双下划线 double underscore),self 代表该类的一个实例。

类中的数据成员和办法成员须要缩进。

class Animal(object):
  def __init__(self, age):
    self.age = age
    self.name = None
    
myAnimal = Animal(3)

不必给 self 提供参数,Python 会主动实现。

两种等价写法:

# 传统办法
c = Coordinate(3,4)
zero = Coordiante(0,0)
print(c.distance(zero))

# 等价写法
c = Coordinate(3,4)
zero = Coordinate(0,0)
print(Coordinate.distance(c,zero))

打印一个对象

c = Coordiante(3,4)
print(c)
<__main__.Coordinate object at 0x7..>
  • 默认是不具体的(uninformative)打印示意
  • 为一个类定义一个 __str__ 办法
  • 当打印一个对象时,Python 调用 __str__ 办法
  • 例如打印 <Coordinate.x , Cooridnate.y>

    class Coordinate(object):
      def __init__(self, x, y):
        self.x = x
        self.y = y
      def distance(self, other):
        x_diff_sq = (self.x-other.x)**2
        y_diff_sq = (self.y-other.x)**2
        return (x_diff_sq + y_diff_sq) ** 0.5
        def __str__(self):
        return "<"+str(self.x)+","+str(self.y)+">"
类型 & isinstance()
print(type(c))
# <class __main__.Coordiante> c 的类型是 Coordinate 类
print(Coordinate)
# <class __main__.Coordiante> Coordinate 是一个类
print(type(Coordinate))
# <type 'type'> Coordinate 也是一种对象

应用 isinstance() 查看某个变量是否为一个类的实例

print(isinstance(c, Coordinate))
# True
其它办法
__add__(self, other) # self + other
__sub__(self, other) # self - other
__eq__(self, other) # self == other
__lt__(self, other) # self < other
__len__(self, other) # len(self)
__str__(self, other) # print self

getter & setter

getter 用来返回类的属性,setter 用来设置类的属性。

class Animal(object):
  def __init__(self, age):
    self.age = age
    self.name = None
  def get_age(self):
    return self.age
     def get_name(self):
    return self.name
     def set_age(self, newAge):
    self.age = newAge
  def set_name(self, newName=""):
    self.name = newName
  def __str__(self):
    return "animal:" + str(self.name) + ":" + str(self.age)

dot natation

. 来拜访属性(数据和办法)。

a.age
a.get_age()

Python 在信息暗藏方面的缺点

以下行为都是不举荐的:

  • Python 容许在类定义外拜访数据

    print(a.age)
  • Python 容许在类定义外批改数据

    a.age = 'infinite'
  • Python 容许在类定义外为一个实例创立属性

    a.size = "tiny"

默认参数

如果没有给定实参,那么给形参的默认参数会启用。

def set_name(self, newname=""):
  self.name = newname
  
a = Animal(3)
a.set_name()
print(a.get_name()) # ""

a = Animal(3)
a.set_name("fluffy")
print(a.get_name()) # 'fluffy'

继承

子类 / 派生类(child class)能够继承父类 / 超类 / 基类(parent class / super class/ base class)

class Cat(Animal):
  def speak(self):
    print("meow")
  def __str__(self):
    return "cat:" + str(self.name) + ":" + str(self.age)

Cat 能够继承所有 Animal 的属性。

class Person(Animal):
  def __init__(self,name,age):
    Animal.__init__(self,age) # 调用父类构造函数
    self.set_name(name)
    self.friends = []   

类变量

class Rabbit(Animal):
  tag = 1 # 类变量
  def __init__(self,age,parent1=None,parent2=None):
    Animal.__init__(self,age)
    self.parent1 = parent1
    self.parent2 = parent2
    self.rid = Rabbit.tag # rid 是实例变量
    Rabbit.tag += 1

tag 用来给每个 Rabbit 实例举世无双的 id。

文件

一个文本文件能够被视为一系列行。

在读文件内容之前,咱们必须通知 Python 哪个文件可能应用并且咱们要怎么做。这就须要 open() 函数。

open() 函数返回一个“文件句柄”– 一个用于文件操作的变量。

这相似于 word 中“文件 -> 关上”。

handle = open(filename, mode),返回一个 handle 去操作文件,文件名是字符串。mode 是可选项,然而如果读文件应该用 ‘r’,如果写文件应该用 ‘w’。举例:fhand = open('mbox.txt', 'r')

换行符

应用换行符 \n 来示意一行的结尾。

换行符是 一个 字符,而不是两个。

stuff = 'x\ny'
print(stuff) 
# x
# y

file handle 能够被视为字符串的序列,也就是说文件中任意一行都是字符串。所以咱们能够应用 for 语句来迭代该序列。

注:一个序列是一个有序列表

xfile = open('mobx.txt')
for cheese in xfile:
  print(cheese)

计算文件的行数:

fhand = open('mbox.txt')
count = 0
for line in fhand:
  count = count + 1
print('line count', count)

读取整个文件:

把文件的整个内容带着换行符一起读取

fhand = open('xx.txt')
inp = fhand.read()
print(len(inp))

过滤读取:

xfile = open('mobx.txt')
for cheese in xfile:
  cheese = cheese.rstrip()
  if cheese startswith('from'):
        print(cheese)

读取不同的文件:

fname = input('enter file name:')
fhand = open(fanme)
count = 0
for line in fhand:
  if line startswith('sub'):
    count = count + 1
print('there are', count, 'subject lines in', fname)

正则表达式

Python 中应用正则表达式须要导入包:

import re

应用 re.search() 来查看字符串是否匹配正则表达式,相似于应用 find() 在字符串中,返回一个布尔值,取决于是否匹配到了。

能够应用 re.findall() 去提取字符串和正则匹配的局部,返回一个列表,蕴含匹配的子串。

hand = open('xx.txt')
for line in hand:
  line = line.rstrip()
  if line.find('From') >= 0:
    print(line)
    
import re
hand = open('xx.txt')
for line in hand:
  line = line.rstrip()
  if re.search('From', line):
    print(line)

startswith() 雷同,应用 ^

import re
hand = open('xx.txt')
for line in hand:
  line = line.rstrip()
  if re.search('^From', line):
    print(line)

. 匹配任何字符。* 匹配任何次数。+ 一个或更多。

: 最初一个匹配的字符

y = re.findall('[0-9]+', x)
print(y)

贪心匹配会匹配最初一个呈现的匹配。

非贪心匹配会匹配第一个呈现的匹配,应用 ?

网络

Sockets

Python 有内置的 TCP Sockets 反对

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode() 
mysock.send(cmd)

while True:
  data = mysock.recv(512)
  if (len(data) < 1):
    break
  print(data.decode())
mysock.close()  

字符串转字节

应用 .decode() 办法。

import socket

while True:
  data = mysock.recv(512)
  if (len(data) < 1):
    break
  mystring - data.decode()
  print(mystring)

应用 urllib

urllib 是一个库

import urllib.request, urllib.parse, urllib.error

fhand = urllib.request.urlopen('http://data.pr4e.org/remeo.txt')
for line in fhand:
  print(line.decode().strip())

Web 服务

有两种支流的数据交换格局:XML 和 JSON。

XML 和 XML Schema:

<person>
  <lastname>Severance</lastname>
  <age>17</age>
  <dateborn>2001-01-17</dateborn>
</person>

<xs:complexType name="person">
  <xs:sequence>
      <xs:element name="lastname" type="xs:string" />
    <xs:element name="age" type="xs:integer" />
    <xs:element name="dateborn" type="xs:date" />
  </xs:sequence>
</xs:complexType>

JSON(JavaScript Object Notation):

import json
data = '''{"name":"Chunk","phone": {"type":"intl","number":"fsd"},"email": {"hide":"yes"}
}'''

info = json.loads(data)
print('Name:', info["name"])

Set

set 是一种保留不反复数据的构造。

应用 set() 结构一个 set,能够传入一个列表并去掉反复元素。

li = [1,2,3,1]
sets = set(li) // [1,2,3]
len(sets) // 3
正文完
 0