pytho(1)--nowcoder

如下内容来自牛客网python教程,仅供自己学习参考。

编码

默认情况下,python3使用的都是UTF-8编码,所有的字符串使用uunicode,当然也可以通过源文件修改编码方式。

标识符
  • 首字母必须是字母或者下划线
  • 其他部分由字母,数字,下划线组成
  • 大小写敏感
    另外在python3中可以用中文做变量名,非Ascll标识符也是被允许的了
python保留字

python的标准库有keyword模块

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
注释

单行注释用 # 开头,多行注释用’’’ ‘’'或者""" “”"

# 注释
'''
注释
注释
'''
"""
注释
注释
"""
行与缩进

python是直接使用缩进来表示代码块,不需要使用{}。

多行语句

如果一条语句很长,可以用反斜杠来实现多行语句:

num = one + \
      two + \
	  three

但是如果是[],{},()则不需要,直接换行即可:

num = [a, b,
       c]
数字类型(Number)
  • int:整数类型,长整型long在python2中有,python3中没有
  • bool:true/false
  • float:1.23,3E-2
  • complex:1 + 2j ,1.1 + 2.2j
字符串(String)
  • 单引号与双引号作用相同
  • 三引号可以指定一个多行的字符串
  • 反斜杠表示转义,而r’'则不发生转义
  • 字符串级联,“a”,“b”,“c” = “abc”
  • 字符串可以用+连接,用*表示多个重复
  • 索引方式:左到右是从0开始,右到左是-1开始
  • 字符串不可改变,准确的说是String这个对象是不可修改的,每一个对象对应一个内存地址。
  • python中没有单独的字符类型,一个字符就是长度为1的字符串
  • 字符串的截取:变量[头下标:尾下标:步长]
空行

分割两个不同含义或功能的代码,空行也是代码的一部分

等待用户输入
input()
同一行显示多条语句

语句之间用分号;分割

print输出

print默认输出是换行的,如果想不换行就在默认加end=" "

print("a", end=" ")
print("b", end=" ")
import 和form … import

import 将整个模块导入
from … import 从某个模块导入某个函数

import sys
from sys import path
命令行参数

python -h

python的基本数据类型

python中不需要声明变量,每个变量在使用前必须赋值,赋值后就代表该变量被创建。

多变量赋值

a,b,c = 1,2,abc

标准数据类型
  • Number:
    int, float, bool, complex
a = 111
type(a)
a = 111
isinstance(a, int)

type和isinstance的区别是,type不会认为子类是父类的一种问题,而isinstance认为子类是父类的一种类型。

数值运算: + - * / (取浮点数) //(得到整数) % **(乘方)

复数用a + bj或者compress(a, b)表示

  • String
    python中的字符串使用单引号或者双引号括起来表示,同时使用反斜杠转义特殊字符。
    字符串截取:左闭右开
  • List
    list是python中使用最频繁的数据类型,列表中的元素可以不相同,支持数字字符串甚至列表的嵌套,另外列表中的元素是可以修改的。
  • tuple
    元组与列表类似,同样其中的数据类型可以不同,不同之处在于元组中元素不可以修改。
    另外在0个或者1个元素上面有特殊的语法规则
tup = ()   # 空元组
tup = (10,)  # 表示一个元素,需要在元素后添加逗号
  • set
    集合由一个或者数个形态各异的整体组成,构成集合的事物或对象称为元素或者是成员。
    创建规则{}或者是set(),但是空集合只能是set(),{}只能表示创建空字典。

基本功能:集合的关系测试以及重复数据的删除

num = {1,2,1,3,4,3}
print(num) #删除重复的数字

集合的差集,并集,交集,异或
  • dictionary
    字典是python中非常常用的一种数据类型,列表中是有序的对象集合,字典是无序的对象集合。
    字典是一种映射关系,通过key-value来表示,key是不可变得,并且在字典中是唯一的。
python的运算符

算术运算符:

+
-
*
/
%
**
//

比较运算符:

==
!=
>
<
>=
<=

赋值运算符

=
+=
-=
*=
/=
%=
**=
//=

位运算符

&
|
^
~
<<
>>

逻辑运算符

and
or
not

成员运算符

in
not in

身份运算符

is
is not
通过判断内存地址来判断是否为同一个对象

运算符的优先级
在这里插入图片描述

数学函数

math.
abs(x) 绝对值
ceil(x) 向上取整
cmp(x,y) x<y 返回-1, x=y返回0, x>y 返回1,python3中废除
exp(x) 求e的x次幂
fabs(x) 返回数字的绝对值的浮点数
floor(x) 向下取整
log(x) log(100,10)=2.0
log10(x): 同理上
max(x1,x2…) 返回给定参数的最大值
min(x1,x2…) 返回给定参数的最小值
modf(x) 返回x的整数部分和小数部分,两个部分的数值符号与x的相同,整数部分以浮点型表示。
pow(x,y) x**y运算后的值
round(x,[,n]) 返回浮点数x的四舍五入的值,n值代表四舍五入的位数
sqrt(x) 返回数字的x的平方根

随机数函数

random.
choice(seq) 从列表中随机挑选一个函数,eg:random.choice(range(10)),从0-9随机挑选一个
randrange([start,] stop [,step]) 指定范围内递增集合获取一个随机数
random(): 随机生成一个实数
seed(): 改变随机数生成器的种子
shuffle(list): 将序列的所有元素随机排序
uniform(x,y): 随机生成一个实数,范围在[x,y]之内

三角函数

acos(x)
asin(x)
atan(x)
atan2(y,x)
sin(x)
cos(x)
tan(x)
hypot(x,y)
degrees(x)
radians(x)

数学常量

pi:Π
e:自然常数

python字符串格式化

在这里插入图片描述

python三引号

python的三引号允许字符串跨多行,字符串中可以包含换行符,制表符以及其他特殊字符。

unicode字符串

python3中所有的字符串都是unicode的字符串

python字符串内建函数

capitalize(): 将字符串第一个字符转换为大写
center(width, fillchar): 返回一个指定宽度的width居中的字符串,fillchar为填充字符,默认为空格
count(str, beg=0, end=(string)): 返回字符串str出现的次数,范围是beg和end之间
decode: python3中没有decode方法,解码给定的bytes对象
encode: 指定编码格式字符串
endswith(suffix, beg=0, end=len(string)):检查字符串是否以obj结尾,也可以指定范围
expandtabs(tabsize=8): 将string中的tab符号转换为空格,tab默认的空格数是8
find(str, beg=0, end=len(string)): 检测str是否包含在字符串之内,可指定范围
index(str, beg=0, end=len(string)): 和find一样,只不过如果搜索不到的话会报错
isalnum(): 如果字符串至少有一个字符并且所有字符都是字母或者数字返回true
isalpha(): 所有都是字母则返回true
isdigit(): 都是数字返回true
islower(): 所有都是小写字符则返回true
isnumeric():只包含数字字符则返回true
isspace(): 字符串只包含空格,则返回true
istitle(): 字符串是标题化的则返回true
isupper(): 所有字符都是大写,则返回true
join(seq): 以指定的字符串作为分割符,将seq中所有的元素的合并成一个新的字符串
len(string):返回字符串的长度
ljust(width[, fillchar]):返回原字符串左对齐,并使用fillchar填充新字符串,默认空格
lower(): 所有的大写转小写
lstrip(): 截掉字符串左边的空格或指定字符
maketrans(): 字符映射转换表
max(str): 返回字符串的最大字符
min(str): 返回字符串的最小字符
replace(old, new[, max]): 用新的替换老的,并且替换次数不超过max次
rfind(str, beg=0,end=len(string)): 和find一样,只不过是从右边开始查询
rindex( str, beg=0, end=len(string)) :和index一样,只不过是从右边开始查找
rjust(width,[, fillchar]):返回一个原字符串右对齐,并使用fillchar填充
rstrip() :删除字符串末尾的空格
split(str="", num=string.count(str)) :以str截取字符串,如果有num,则截取num+1个字符串
splitlines([keepends]) :按照空格,换行符进行分割字符串,返回一个列表
startswith(substr, beg=0,end=len(string)):检查字符串是否以指定的字符串开头,beg,end指定范围
strip(): 清空字符串的首尾空格
swapcase() :将字符串中的字符大写转小写,小写转大写
title() :返回标题式的字符串,单词大写开头,其余字母都是小写
translate(table, deletechars="") :根据给出的表去转换string字符,把要过滤的放在deletechars参数中
upper() :小写转大写
zfill (width):返回长度为width的字符串,原字符串右对齐,用0填充
isdecimal():检查字符串是否包含十进制字符

python中的列表

python中有六大序列的内置类型 列表、元组、字符串、Unicode字符串、buffer对象和 xrange 对象,所有的序列操作都包括索引,切片,加,乘,检查成员。

访问列表中的值:
下标 list[0]
切片 list[1:5] 左闭右开

更新列表:
list[2] = 1
list[2] = 2

删除列表元素:
del list[2]

操作符:
len(list[])
list1[] + list2[]
[] * 4
3 in list[]

列表嵌套:
[[1,2,3],[4,5,6]]

函数,方法:
len(list)
max(list)
min(list)
list(seq): 将元组转换为列表

list.append(obj)
list.count(obj)
list.extend(seq) :在末尾新加一个序列的多个值
list.index(obj)
list.insert(index, obj)
list.pop([index=-1])
list.remove(obj)
list.reverse()
list.sort( key=None, reverse=False)
list.clear()
list.copy()

元组

元组和列表类似,不同之处在于元组的元素不能修改
创建空元组:tup1 = ()
当元组中只有一个元素的时候,需要在元素后面加逗号 tup = (1,),不然像前面那个1会被判定为整型

与列表一样可以组合,切片
元组的元素是不可以修改的,可以通过拼接的方式得到新的数组
同样元组中的元素也是不可以删除的,但是可以通过del删除整个元组

python字典

键值对,键必须是唯一的,如字符串,数字,元组
del删除 clear

字典键的特性:
1.同一个键不可以出现两次
2.不可以用list

字典的内置函数和方法:
len(dict): 计算元素的个数,即键的总数
str(dict): 输出字典

clear()
copy()
fromkeys(): 创建一个新字典,用seq中的元素作为字典的键,val为字典所有键对应的初始值
get(key, default=None) :返回指定键的值
key in dict:键在字典中返回true
items() :返回可遍历的键值元组数组
keys() :返回键,可用list()转换为列表
setdefault(key, default=None) :和get类似
update(dict2) :将dict2中的字典更新到dict中
values() :返回值,可用list()转换为列表
pop(key[,default]) :删除指定键所对应的值
popitem() :随机删除字典中最后一对键值

集合

集合set是一个无序不重复的元素序列
可以使用大括号{} 或者 set()来创建一个集合,但是空集合只能用set()创建,{}表示空字典

重复元素可以用集合来去重
集合的运算

集合的add,update,remove,discard(如果元素不存在则不会报错),pop,len,clear,copy

条件控制

if
elif
else

循环语句
  • while 循环
n = 100
sum = 0
counter = 1
while counter <= n: 
	sum = sum + counter
    counter += 1
print("1 到 %d 之和为: %d" % (n,sum))

无限循环可以使用ctrl + c来停止

  • for循环
    range():生成数列,与len()常连用。
    list(range(5))

break和continue
break结束整个循环,continue结束当前循环

for循环中可以假如else语句,else在循环结束结束或者条件为false的时候执行,break打断的时候不会执行。

pass语句:
pass是空语句,为了保持结果的完整性

迭代器和生成器

迭代是访问集合元素的一种方式
迭代器从集合的第一个元素开始访问,直到所有的元素被访问完毕,迭代器只能前进不能后退。

iter():

>>> list=[1,2,3,4]
>>> it = iter(list)    # 创建迭代器对象

for x in it:
    print (x, end=" ")

也可以使用next()函数:

import sys         # 引入 sys 模块
 
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
 
while True:
    try:
        print (next(it))
    except StopIteration:
        sys.exit()

创建一个迭代器:
想要把一个类作为一个迭代器使用需要两个方法:
iter()返回一个特殊的迭代器对象,这个对象实现了next()方法,并通过 StopIteration 异常标识迭代的完成。
next()方法会返回下一个迭代器对象

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    x = self.a
    self.a += 1
    return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

StopIteration
StopIteration 异常用于标识迭代的完成,防止出现无限循环的情况,在 next() 方法中我们可以设置在完成指定循环次数后触发 StopIteration 异常来结束迭代。

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    if self.a <= 20:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
  print(x)

生成器:
生成器是一个返回迭代器的函数,在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。调用一个生成器函数,返回的是一个迭代器对象。

#!/usr/bin/python3

import sys

def fibonacci(n): # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成

while True:
    try:
        print (next(f), end=" ")
    except StopIteration:
        sys.exit()
python 函数

定义函数的规则:

def 函数名(参数列表):
    函数体

函数调用
函数传递

可更改对象和不可更改对象
strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。

  • 不可变类型:变量赋值 a=5 后再赋值 a=10,这里实际是新生成一个 int 值对象 10,再让 a 指向它,而 5 被丢弃,不是改变a的值,相当于新生成了a。
  • 可变类型:变量赋值 la=[1,2,3,4] 后再赋值 la[2]=5 则是将 list la 的第三个元素值更改,本身la没有动,只是其内部的一部分值被修改了。

python 传不可变对象实例:

#!/usr/bin/python3

def ChangeInt( a ):
    a = 10

b = 2
ChangeInt(b)
print( b ) # 结果是 2

传可变对象实例:

#!/usr/bin/python3

# 可写函数说明
def changeme( mylist ):
   "修改传入的列表"
   mylist.append([1,2,3,4])
   print ("函数内取值: ", mylist)
   return

# 调用changeme函数
mylist = [10,20,30]
changeme( mylist )
print ("函数外取值: ", mylist)
  • 必需参数
    调用时必须传入参数,否则会报错
  • 关键字参数
    函数根据关键字参数确定传入的参数值,若使用关键字参数调用参数的顺序和声明的不一致,python解释器可以通过参数名匹配到参数值。
#!/usr/bin/python3

#可写函数说明
def printinfo( name, age ):
   "打印任何传入的字符串"
   print ("名字: ", name)
   print ("年龄: ", age)
   return

#调用printinfo函数
printinfo( age=50, name="nowcoder" )
  • 默认参数
    调用函数时,如果没有传递参数,则使用默认参数
#!/usr/bin/python3

#可写函数说明
def printinfo( name, age = 35 ):
   "打印任何传入的字符串"
   print ("名字: ", name)
   print ("年龄: ", age)
   return

#调用printinfo函数
printinfo( age=50, name="nowcoder" )
print ("------------------------")
printinfo( name="nowcoder" )
  • 不定长参数
    当我们需要处理比声明开始的时候更多的参数,那么这些参数就是不定长参数,且在声明时不会命名。
#!/usr/bin/python3

# 可写函数说明
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   print (vartuple)

# 调用printinfo 函数
printinfo( 70, 60, 50 )

以星号传入的参数会以元组的形式导入,存放所有未命名的变量参数。
同时也可以给不定项参数传递未命名的变量。

还有一种是以两个星的参数,与一个星不同的是,两个星是以字典的方式传入的

#!/usr/bin/python3

# 可写函数说明
def printinfo( arg1, **vardict ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   print (vardict)

# 调用printinfo 函数
printinfo(1, a=2,b=3)

输出: 
1
{'a': 2, 'b': 3}
  • 匿名函数
    python使用lamdba创建匿名函数,所谓匿名就是不在需要传统的def去创建函数:
    lamdba的主体不是一个代码块,而是一个表达式;
    lamdba有自己的命名空间,不能访问自己定义列表之外或全局命名空间里的参数;
    eg:
格式:
lambda [arg1 [,arg2,.....argn]]:expression

#!/usr/bin/python3

# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2

# 调用sum函数
print ("相加后的值为 : ", sum( 10, 20 ))
print ("相加后的值为 : ", sum( 20, 20 ))
  • return 语句
#!/usr/bin/python3

# 可写函数说明
def sum( arg1, arg2 ):
   # 返回2个参数的和."
   total = arg1 + arg2
   print ("函数内 : ", total)
   return total

# 调用sum函数
total = sum( 10, 20 )
print ("函数外 : ", total)
python的数据结构
  • 列表
    列表可变,字符串和元组不可以。
    列表中的一些方法:
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(a.count(333), a.count(66.25), a.count('x'))
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
  • 将列表当作堆栈使用
    先进后出
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
  • 将列表当作队列使用
    效率低,不建议
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
  • 列表表达式
>>> vec1 = [2, 4, 6]
>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]
  • 嵌套列表解析
    3x4的矩阵列表:
>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

将3X4的矩阵列表转换为4X3列表:
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
  • 元组和序列
    通常元组在输出时总是带有括号的,在输入是可能没有。
  • del语句
    del可以通过索引来删除某一个值,或通过切割的方式删除,或删除整个列表:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
  • 集合
    集合是一个无序不重复的集合,用{}表示,如果创建一个空集合,要用set(),而不是{},{}用来表示空字典。
    主要功能有删除重复元素,检测成员是否在里面,以及一些集合的基本操作。
  • 字典
    序列是以连续的整数为索引,字典是以关键字为索引,关键字是任意不可变类型,通常是字符串或者数值。
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
  • 遍历技巧
    在遍历字典时使用items()可以将键和值都读取出来
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

在遍历序列时,索引位置和值可以通过enumerate()读取出来。

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

同时遍历多个序列,可以用zip()

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

反向遍历:

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

按顺序遍历:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear
python模块
import sys
 
print('命令行参数如下:')
for i in sys.argv:
   print(i)
 
print('\n\nPython 路径为:', sys.path, '\n')


output:
命令行参数如下:
using_sys.py
参数1
参数2


Python 路径为: ['/root', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages'] 

import的是引入标准库中的sys模块,sys.argv是一个包含命令行参数的列表,sys.path()包含了自动查找所需模块的路径

python中的from可以从模块中导入一个指定的部分到当前命名空间中,

>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

上面的操作不会将整个fibo模块导入,只会导入其中的fib函数

name()属性:
一个模块被另一个程序第一次引入时,模块中的主程序将运行,如果我们想让模块中的某一程序不运行,我们可以用name属性来使程序块只在模块自身运行时执行。

#!/usr/bin/python3
# Filename: using_name.py

if __name__ == '__main__':
   print('程序自身在运行')
else:
   print('我来自另一模块')

$ python
>>> import using_name
我来自另一模块
>>>

dir()函数:
dir()函数会给出模块内的所有名称,以一个字符串列表的形式返回

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)  
['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
 '__package__', '__stderr__', '__stdin__', '__stdout__',
 '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
 '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
 'call_tracing', 'callstats', 'copyright', 'displayhook',
 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
 'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
 'thread_info', 'version', 'version_info', 'warnoptions']

如果什么参数也不传,那么dir函数就列出当前定义的所有名称

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir() # 得到一个当前模块中定义的属性列表
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
>>> a = 5 # 建立一个新的变量 'a'
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>>
>>> del a # 删除变量名a
>>>
>>> dir()
['__builtins__', '__doc__', '__name__', 'sys']

标准模块:
python本身带着一些标准的模块库,虽然不是内置的功能,却可以高效的使用。

包:
包是一种管理管理python模块命名空间的一种形式,比如A.B,那么就是包A的子模块B.
这样的好处是模块之间的全局变量相互影响,也不会担心库之间重名的情况。

python的输入输出

输出格式美化:
str(): 函数返回一个用户易读的表达形式。
repr(): 产生一个解释器易读的表达形式。

>>> s = 'Hello, Nowcoder'
>>> str(s)
'Hello, Nowcoder'
>>> repr(s)
"'Hello, Nowcoder'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'x 的值为: ' + repr(x) + ',  y 的值为:' + repr(y) + '...'
>>> print(s)
x 的值为: 32.5,  y 的值为:40000...
>>> #  repr() 函数可以转义字符串中的特殊字符
... hello = 'hello, nowcoder\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, nowcoder\n'
>>> # repr() 的参数可以是 Python 的任何对象
... repr((x, y, ('Google', 'Nowcoder')))
"(32.5, 40000, ('Google', 'Nowcoder'))"

rjust()方法可以将字符串靠右,并向左填充空格

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # 注意前一行 'end' 的使用
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

>>> for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

zfill()方法会在数字的左边填充0

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

format()的使用:

>>> print('{}网址: "{}!"'.format('牛客教程', 'www.nowcoder.com'))
牛客教程网址: "www.nowcoder.com!"

用数字表示插入的位置

>>> print('{0} 和 {1}'.format('Google', 'Nowcoder'))
Google 和 Nowcoder
>>> print('{1} 和 {0}'.format('Google', 'Nowcoder'))
Nowcoder 和 Google

关键字指向参数

>>> print('{name}网址: {site}'.format(name='牛客教程', site='www.nowcoder.com'))
牛客教程网址: www.nowcoder.com

可以通过传字典的形式,通过[] 访问键值

>>> table = {'Google': 1, 'Nowcoder': 2, 'Taobao': 3}
>>> print('Nowcoder: {0[Nowcoder]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table))
Nowcoder: 2; Google: 1; Taobao: 3

保留小数点:

>>> import math
>>> print('常量 PI 的值近似为 {0:.3f}。'.format(math.pi))
常量 PI 的值近似为 3.142。

旧式的字符串格式化%:

>>> import math
>>> print('常量 PI 的值近似为:%5.3f。' % math.pi)
常量 PI 的值近似为:3.142。

读取键盘输入:
python提供了input()函数用来从标准输入读取一行文本,默认标准输入是键盘。

#!/usr/bin/python3

str = input("请输入:");
print ("你输入的内容是: ", str)

读文件和写文件:
open()将会返回一个file对象,open(filename, mode)
filename包含了要访问的文件名的字符串名称。
mode:决定了打开方式,只读只写,追加,非必须字段,默认只读。

r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
w+ 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "w")

f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" )

# 关闭打开的文件
f.close()

文件对象的方法:
假设已经创建了一个f的文件对象

f.read():
f.read(size)返回一定数目的数据,然后返回字符串或者字节对象返回,size可选,当size不传或者size为负数,那么文件的内容将被全部返回。

f.readline():
f.readline()会从文件中单独读取一行,换行符为’\n‘,如果返回的是一个空的字符串,说明已经读到了最后一行。

f.readlines():
返回该文件的所有行,可选参数sizehint,则指定读取长度,并将这些按字节分割。

f.write():
参数string,将string写入文件中,然后返回写入的字符数。
如果传入的不是字符串,那么要先进行字符串转化

f.tell():
返回文件对象所在的位置,它是从头开始算起的字节数。

f.seek():
如果想改变当前文件的位置,使用f.seek(offset, from_what) 函数。
from_what, 0 表示开头,1表示当前位置,2表示文件结尾
seek(x,0) : 从起始位置即文件首行首字符开始移动 x 个字符
seek(x,1) : 表示从当前位置往后移动x个字符
seek(-x,2):表示从文件的结尾往前移动x个字符

>>> f = open('/tmp/foo.txt', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)     # 移动到文件的第六个字节
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # 移动到文件的倒数第三字节
13
>>> f.read(1)
b'd'

f.close():
当处理完一个文件后,调用close去关闭文件并释放系统资源。

>>> with open('/tmp/foo.txt', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

pickle模块:
pickle模块实现了基本的数据序列化和反序列化。
有了 pickle 这个对象, 就能对 file 以读取的形式打开,x = pickle.load(file)

#!/usr/bin/python3
import pickle

# 使用pickle模块将数据对象保存到文件
data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()
python file方法

open() 方法:
用于打开一个文件,并返回文件对象

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file: 必需,文件路径(相对或者绝对路径)。
mode: 可选,文件打开模式
buffering: 设置缓冲
encoding: 一般使用utf8
errors: 报错级别
newline: 区分换行符
closefd: 传入的file参数类型
opener:

file对象:
1 file.close()关闭文件。关闭后文件不能再进行读写操作。
2 file.flush()刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。
3 file.fileno()返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。
4 file.isatty()如果文件连接到一个终端设备返回 True,否则返回 False。
5 file.next() 返回文件下一行。(Python 3 中的 File 对象不支持 next() 方法)
6 file.read([size])从文件读取指定的字节数,如果未给定或为负则读取所有。
7 file.readline([size])读取整行,包括 “\n” 字符。
8 file.readlines([sizeint])读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。
9 file.seek(offset[, whence])设置文件当前位置
10 file.tell()返回文件当前位置。
11 file.truncate([size])从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。
12 file.write(str)将字符串写入文件,返回的是写入的字符长度。
13 file.writelines(sequence)向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。

python os文件及目录方法
1	os.access(path, mode) 检验权限模式
2	os.chdir(path) 改变当前工作目录
3	os.chflags(path, flags) 设置路径的标记为数字标记。
4	os.chmod(path, mode) 更改权限
5	os.chown(path, uid, gid) 更改文件所有者
6	os.chroot(path) 改变当前进程的根目录
7	os.close(fd) 关闭文件描述符 fd
8	os.closerange(fd_low, fd_high) 关闭所有文件描述符,从 fd_low (包含) 到 fd_high (不包含), 错误会忽略
9	os.dup(fd) 复制文件描述符 fd
10	os.dup2(fd, fd2) 将一个文件描述符 fd 复制到另一个 fd2
11	os.fchdir(fd) 通过文件描述符改变当前工作目录
12	os.fchmod(fd, mode) 改变一个文件的访问权限,该文件由参数fd指定,参数mode是Unix下的文件访问权限。
13	os.fchown(fd, uid, gid) 修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符fd指定。
14	os.fdatasync(fd) 强制将文件写入磁盘,该文件由文件描述符fd指定,但是不强制更新文件的状态信息。
15	os.fdopen(fd[, mode[, bufsize]]) 通过文件描述符 fd 创建一个文件对象,并返回这个文件对象
16	os.fpathconf(fd, name) 返回一个打开的文件的系统配置信息。name为检索的系统配置的值,它也许是一个定义系统值的字符串,这些名字在很多标准中指定(POSIX.1, Unix 95, Unix 98, 和其它)。
17	os.fstat(fd) 返回文件描述符fd的状态,像stat()。
18	os.fstatvfs(fd) 返回包含文件描述符fd的文件的文件系统的信息,Python 3.3 相等于 statvfs()。
19	os.fsync(fd) 强制将文件描述符为fd的文件写入硬盘。
20	os.ftruncate(fd, length) 裁剪文件描述符fd对应的文件, 所以它最大不能超过文件大小。
21	os.getcwd() 返回当前工作目录
22	os.getcwdu() 返回一个当前工作目录的Unicode对象
23	os.isatty(fd) 如果文件描述符fd是打开的,同时与tty(-like)设备相连,则返回true, 否则False。
24	os.lchflags(path, flags) 设置路径的标记为数字标记,类似 chflags(),但是没有软链接
25	os.lchmod(path, mode) 修改连接文件权限
26	os.lchown(path, uid, gid) 更改文件所有者,类似 chown,但是不追踪链接。
27	os.link(src, dst) 创建硬链接,名为参数 dst,指向参数 src
28	os.listdir(path) 返回path指定的文件夹包含的文件或文件夹的名字的列表。
29	os.lseek(fd, pos, how) 设置文件描述符 fd当前位置为pos, how方式修改: SEEK_SET 或者 0 设置从文件开始的计算的pos; SEEK_CUR或者 1 则从当前位置计算; os.SEEK_END或者2则从文件尾部开始. 在unix,Windows中有效
30	os.lstat(path) 像stat(),但是没有软链接
31	os.major(device) 从原始的设备号中提取设备major号码 (使用stat中的st_dev或者st_rdev field)。
32	os.makedev(major, minor) 以major和minor设备号组成一个原始设备号
33	os.makedirs(path[, mode]) 递归文件夹创建函数。像mkdir(), 但创建的所有intermediate-level文件夹需要包含子文件夹。
34	os.minor(device) 从原始的设备号中提取设备minor号码 (使用stat中的st_dev或者st_rdev field )。
35	os.mkdir(path[, mode]) 以数字mode的mode创建一个名为path的文件夹.默认的 mode 是 0777 (八进制)。
36	os.mkfifo(path[, mode]) 创建命名管道,mode 为数字,默认为 0666 (八进制)
37	os.mknod(filename[, mode=0600, device]) 创建一个名为filename文件系统节点(文件,设备特别文件或者命名pipe)。
38	os.open(file, flags[, mode]) 打开一个文件,并且设置需要的打开选项,mode参数是可选的
39	os.openpty() 打开一个新的伪终端对。返回 pty 和 tty的文件描述符。
40	os.pathconf(path, name) 返回相关文件的系统配置信息。
41	os.pipe() 创建一个管道. 返回一对文件描述符(r, w) 分别为读和写
42	os.popen(command[, mode[, bufsize]]) 从一个 command 打开一个管道
43	os.read(fd, n) 从文件描述符 fd 中读取最多 n 个字节,返回包含读取字节的字符串,文件描述符 fd对应文件已达到结尾, 返回一个空字符串。
44	os.readlink(path) 返回软链接所指向的文件
45	os.remove(path) 删除路径为path的文件。如果path 是一个文件夹,将抛出OSError; 查看下面的rmdir()删除一个 directory。
46	os.removedirs(path) 递归删除目录。
47	os.rename(src, dst) 重命名文件或目录,从 src 到 dst
48	os.renames(old, new) 递归地对目录进行更名,也可以对文件进行更名。
49	os.rmdir(path) 删除path指定的空目录,如果目录非空,则抛出一个OSError异常。
50	os.stat(path) 获取path指定的路径的信息,功能等同于C API中的stat()系统调用。
51	os.stat_float_times([newvalue]) 决定stat_result是否以float对象显示时间戳
52	os.statvfs(path) 获取指定路径的文件系统统计信息
53	os.symlink(src, dst) 创建一个软链接
54	os.tcgetpgrp(fd) 返回与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组
55	os.tcsetpgrp(fd, pg) 设置与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组为pg。
56	os.tempnam([dir[, prefix]]) Python3 中已删除。返回唯一的路径名用于创建临时文件。
57	os.tmpfile() Python3 中已删除。返回一个打开的模式为(w+b)的文件对象 .这文件对象没有文件夹入口,没有文件描述符,将会自动删除。
58	os.tmpnam() Python3 中已删除。为创建一个临时文件返回一个唯一的路径
59	os.ttyname(fd) 返回一个字符串,它表示与文件描述符fd 关联的终端设备。如果fd 没有与终端设备关联,则引发一个异常。
60	os.unlink(path) 删除文件路径
61	os.utime(path, times) 返回指定的path文件的访问和修改的时间。
62	os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) 输出在文件夹中的文件名通过在树中游走,向上或者向下。
63	os.write(fd, str) 写入字符串到文件描述符 fd中. 返回实际写入的字符串长度
64	os.path 模块 获取文件的属性信息。
python错误及异常

语法错误:
xxxxxx

异常:
异常以不同的类型出现,这些类型作为信息的一部分展示出来。

>>>10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: Can't convert 'int' object to str implicitly

异常处理:

>>>while True:
        try:
            x = int(input("Please enter a number: "))
            break
        except ValueError:
            print("Oops!  That was no valid number.  Try again   ")

except处理的异常可以传一个元组

except (RuntimeError, TypeError, NameError):
        pass

try后面可以加else语句,但是else要放在except之后,在没有任何异常的时候执行else里面的语句

抛出异常:
python使用raise语句抛出一个指定的异常,raise中指定了要抛出的异常的参数,这个异常必须是异常的实例或者是异常的类,如果只想知道这是一个异常而不去处理它,那么用raise抛出就好。

>>>try:
        raise NameError('HiThere')
    except NameError:
        print('An exception flew by!')
        raise

An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: HiThere

用户自定义异常
用户可以自定义一个异常,异常类继承exception类,可以直接继承,也可以间接继承

>>>class MyError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)

>>> try:
        raise MyError(2*2)
    except MyError as e:
        print('My exception occurred, value:', e.value)

My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

定义清理行为:
即finally,不管执行结果怎么样,都会执行finally子句

>>>def divide(x, y):
        try:
            result = x / y
        except ZeroDivisionError:
            print("division by zero!")
        else:
            print("result is", result)
        finally:
            print("executing finally clause")

>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

预定义的清理行为:
关键字with语句可以保证文件之类的执行完会正确处理它的清理方法

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")
python面向对象

python的设计之初就是一门面向对象的语言。

面向对象技术简介:
类(class):用来描述相同属性和方法的对象的集合。对象是类的实例

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>
 # 类实例化之后可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性

方法:类中定义的函数
类变量:类变量的整个实例化是公用的,类变量定义在类中,且函数体之外,类变量通常不作为实例变量使用。
数据成员:类变量或者实例变量用于处理类及其实例对象的相关数据。
方法重写:如果父类继承的方法不能满足子类的需求,那么可以对其进行改写,这个过程叫覆盖,也是重写。
局部变量:定义在方法中的变量,只作用于当前实例的类。
实例变量:在类的声明中,属性是用变量表示的,这种变量称为实例变量
继承:即一个派生类继承基类的字段和方法
实例化:创建一个类的实例,类的具体对象
对象:通过类定义的数据结构实例,对象包括数据成员和方法

# 类对象支持两种操作,属性引用和实例化

#!/usr/bin/python3

class MyClass:
    """一个简单的类实例"""
    i = 12345
    def f(self):
        return 'hello world'

# 实例化类
x = MyClass()

# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())

类中有一个init()特殊方法(构造方法),该方法会在实例化的过程中自动调用:

def __init__(self):
    self.data = []

实例化也会调用init()方法,也可以传参数

#!/usr/bin/python3

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i)   # 输出结果:3.0 -4.5

self代表类的实例,而非类:
类的方法和普通的函数只有一个特别的区别,它们必须有一个额外的第一参数名称,按照惯例它的名称是self。

class Test:
    def prt(self):
        print(self)
        print(self.__class__)

t = Test()
t.prt()

<__main__.Test instance at 0x100771878>
__main__.Test

# self不是关键字,换成其他的也可以

类的方法:
在类的内部,使用def关键字来定义一个方法,与一般函数定义不同,类的函数方法必须有self参数,且为第一个参数,self代表类的实例。

继承:
···
class DerivedClassName(BaseClassName1):

.
.
.

···
需要注意圆括号中基类的顺序,若基类中有相同的方法名,而在子类使用时未指定,即从左到右搜索。

#!/usr/bin/python3

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))

#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))



s = student('ken',10,60,3)
s.speak()


ken 说: 我 10 岁了,我在读 3 年级

多继承:

#!/usr/bin/python3

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))

#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))

#另一个类,多重继承之前的准备
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))

#多重继承
class sample(speaker,student):
    a =''
    def __init__(self,n,a,w,g,t):
        student.__init__(self,n,a,w,g)
        speaker.__init__(self,n,t)

test = sample("Tim",25,80,4,"Python")
test.speak()   #方法名同,默认调用的是在括号中排前地父类的方法

方法重写:
如果父类方法不能满足需求,可以在子类中重写父类方法。

#!/usr/bin/python3

class Parent:        # 定义父类
   def myMethod(self):
      print ('调用父类方法')

class Child(Parent): # 定义子类
   def myMethod(self):
      print ('调用子类方法')

c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法
super(Child,c).myMethod() #用子类对象调用父类已被覆盖的方法

类的属性和方法:
私有属性:__private_attrs,不能在类外部或者直接使用,内部使用时self.__private_attrs
类的私有方法:__private_method,同样的self.__private_methods

#!/usr/bin/python3

class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print (self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount)  # 报错,实例不能访问私有变量


1
2
2
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    print (counter.__secretCount)  # 报错,实例不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'
#!/usr/bin/python3

class Site:
    def __init__(self, name, url):
        self.name = name       # public
        self.__url = url   # private

    def who(self):
        print('name  : ', self.name)
        print('url : ', self.__url)

    def __foo(self):          # 私有方法
        print('这是私有方法')

    def foo(self):            # 公共方法
        print('这是公共方法')
        self.__foo()

x = Site('牛客教程', 'www.nowcoder.com')
x.who()        # 正常输出
x.foo()        # 正常输出
x.__foo()      # 报错


#!/usr/bin/python3

class Site:
    def __init__(self, name, url):
        self.name = name       # public
        self.__url = url   # private

    def who(self):
        print('name  : ', self.name)
        print('url : ', self.__url)

    def __foo(self):          # 私有方法
        print('这是私有方法')

    def foo(self):            # 公共方法
        print('这是公共方法')
        self.__foo()

x = Site('牛客教程', 'www.nowcoder.com')
x.who()        # 正常输出
x.foo()        # 正常输出
x.__foo()      # 报错

运算符重载

#!/usr/bin/python3

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)

   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)


Vector(7,8)
python的命名空间和作用域

命名空间:参考电脑上文件,相同空间的文件不可以重名,不同空间的可以重名。

全局变量和局部变量:

#!/usr/bin/python3

total = 0 # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
    #返回2个参数的和."
    total = arg1 + arg2 # total在这里是局部变量.
    print ("函数内是局部变量 : ", total)
    return total

#调用sum函数
sum( 10, 20 )
print ("函数外是全局变量 : ", total)

函数内是局部变量 :  30
函数外是全局变量 :  0

global 和 nonlocal关键字:

#!/usr/bin/python3

num = 1
def fun1():
    global num  # 需要使用 global 关键字声明
    print(num) 
    num = 123
    print(num)
fun1()
print(num)

如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字了

#!/usr/bin/python3

def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal关键字声明
        num = 100
        print(num)
    inner()
    print(num)
outer()
python标准库概览

操作系统接口:

>>> import os
>>> os.getcwd()      # 返回当前的工作目录
'C:\\Python34'
>>> os.chdir('/server/accesslogs')   # 修改当前的工作目录
>>> os.system('mkdir today')   # 执行系统命令 mkdir 
0

>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>

文件通配符:
glob提供函数从目录通配符搜索生成文件列表:

>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']

命令行参数
通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。例如在命令行中执行 “python demo.py one two three” 后可以得到以下输出结果:

>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']

错误输出重定向和程序中止:

>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one

字符串正则匹配:
re模块为高级字符串的处理提供了正则表达式工具:

>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

数学:
math模块为浮点运算提供了底层c函数库的访问

>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0
>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4

访问互联网:
有几个模块用于访问互联网及其网络通信协议,其中最简单的两个是用于处理从url上接收数据的urllib.request以及收发邮件的smtplib:

>>> from urllib.request import urlopen
>>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
...     line = line.decode('utf-8')  # Decoding the binary data to text.
...     if 'EST' in line or 'EDT' in line:  # look for Eastern Time
...         print(line)

<BR>Nov. 25, 09:43:32 PM EST

>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()

时间和日期:
datetime模块为时间和日期的处理提供了方法:

>>> # dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368

数据压缩:
以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile:

>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979

性能度量:
当需要验证同一问题的不同方法的性能问题
eg:timeit提供了时间度量工具

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791

:mod:profile 和 pstats 模块提供了针对更大代码块的时间度量工具.

测试模块:
doctest模块提供了一个工具,扫描模块并根据程序中内嵌的文档字符串执行测试。
通过用户提供的例子,它强化了文档,允许 doctest 模块确认代码的结果是否与文档一致:

def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

import doctest
doctest.testmod()   # 自动验证嵌入测试

unittest模块不像 doctest模块那么容易使用,不过它可以在一个独立的文件里提供一个更全面的测试集:

import unittest

class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        self.assertRaises(ZeroDivisionError, average, [])
        self.assertRaises(TypeError, average, 20, 30, 70)

unittest.main() # Calling from the command line invokes all tests
python3中的内置函数

abs():返回数字的绝对值

#!/usr/bin/python3

print ("abs(-40) : ", abs(-40))
print ("abs(100.10) : ", abs(100.10))

abs(-40) :  40
abs(100.10) :  100.1

dict(): 创建一个字典

>>>dict()                        # 创建空字典
{}
>>> dict(a='a', b='b', t='t')     # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3]))   # 映射函数方式来构造字典
{'three': 3, 'two': 2, 'one': 1} 
>>> dict([('one', 1), ('two', 2), ('three', 3)])    # 可迭代对象方式来构造字典
{'three': 3, 'two': 2, 'one': 1}

help():用于查看函数或模块用途的详细说明

>>>help('sys')             # 查看 sys 模块的帮助
……显示帮助信息……

>>>help('str')             # 查看 str 数据类型的帮助
……显示帮助信息……

>>>a = [1,2,3]
>>>help(a)                 # 查看列表 list 帮助信息
……显示帮助信息……

>>>help(a.append)          # 显示list的append方法的帮助
……显示帮助信息……

min():返回给定参数的最小值,参数可以为序列

#!/usr/bin/python3

print ("min(80, 100, 1000) : ", min(80, 100, 1000))
print ("min(-20, 100, 400) : ", min(-20, 100, 400))
print ("min(-80, -20, -10) : ", min(-80, -20, -10))
print ("min(0, 100, -400) : ", min(0, 100, -400))

setattr():对应函数 getattr(),用于设置属性值,该属性不一定是存在的

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, 'bar')          # 获取属性 bar 值
1
>>> setattr(a, 'bar', 5)       # 设置属性 bar 值
>>> a.bar
5



>>>class A():
...     name = "nowcoder"
... 
>>> a = A()
>>> setattr(a, "age", 28)
>>> print(a.age)
28

all():用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。
元素除了是 0、空、None、False 外都算 True。

>>> all(['a', 'b', 'c', 'd'])  # 列表list,元素都不为空或0
True
>>> all(['a', 'b', '', 'd'])   # 列表list,存在一个为空的元素
False
>>> all([0, 1,2, 3])          # 列表list,存在一个为0的元素
False

>>> all(('a', 'b', 'c', 'd'))  # 元组tuple,元素都不为空或0
True
>>> all(('a', 'b', '', 'd'))   # 元组tuple,存在一个为空的元素
False
>>> all((0, 1, 2, 3))          # 元组tuple,存在一个为0的元素
False

>>> all([])             # 空列表
True
>>> all(())             # 空元组
True

dir():不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法dir(),该方法将被调用。如果参数不包含dir(),该方法将最大限度地收集参数信息。

>>>dir()   #  获得当前模块的属性列表
['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
>>> dir([ ])    # 查看列表的方法
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

hex():用于将一个指定数字转换为 16 进制数

>>>hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
>>> hex(12)
'0xc'
>>> type(hex(12))
<class 'str'>      # 字符串

next():返回迭代器的下一个项目

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
    try:
        # 获得下一个值:
        x = next(it)
        print(x)
    except StopIteration:
        # 遇到StopIteration就退出循环
        break

slice():实现切片对象,主要用在切片操作函数里的参数传递。

>>>myslice = slice(5)    # 设置截取5个元素的切片
>>> myslice
slice(None, 5, None)
>>> arr = range(10)
>>> arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arr[myslice]         # 截取 5 个元素
[0, 1, 2, 3, 4]

any():用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。

>>>any(['a', 'b', 'c', 'd'])  # 列表list,元素都不为空或0
True

>>> any(['a', 'b', '', 'd'])   # 列表list,存在一个为空的元素
True

>>> any([0, '', False])        # 列表list,元素全为0,'',false
False

>>> any(('a', 'b', 'c', 'd'))  # 元组tuple,元素都不为空或0
True

>>> any(('a', 'b', '', 'd'))   # 元组tuple,存在一个为空的元素
True

>>> any((0, '', False))        # 元组tuple,元素全为0,'',false
False

>>> any([]) # 空列表
False

>>> any(()) # 空元组
False

divmod():
接收两个数字类型(非复数)参数,返回一个包含商和余数的元组(a // b, a % b)

>>> divmod(7, 2)
(3, 1)
>>> divmod(8, 2)
(4, 0)
>>> divmod(8, -2)
(-4, 0)
>>> divmod(3, 1.3)
(2.0, 0.3999999999999999)

id():
用于获取对象的内存地址。

>>>a = 'nowcoder'
>>> id(a)
4531887632
>>> b = 1
>>> id(b)
140588731085608

sorted():
对所有可迭代的对象进行排序操作
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作.

>>>sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]                      # 默认为升序

>>>a=[5,2,3,1,4]
>>> a.sort()
>>> a
[1,2,3,4,5]

>>>sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]

>>>example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> sorted(example_list, reverse=True)
[7, 6, 5, 4, 3, 2, 1, 0]

ascli():
类似 repr() 函数, 返回一个表示对象的字符串, 但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符。 生成字符串类似 Python2 版本中 repr() 函数的返回值

>>> ascii('nowcoder')
"'nowcoder'"

enumerate():
用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>>list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>>list(enumerate(seasons, start=1))       # 小标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

>>>seq = ['one', 'two', 'three']
>>>for i, element in enumerate(seq):
...    print(i, seq[i])
... 
0 one
1 two
2 three

input():
Python3.x 中 input() 函数接受一个标准输入数据,返回为 string 类型

>>>a = input("input:")
input:123                  # 输入整数
>>> type(a)
<class 'str'>              # 字符串
>>> a = input("input:")    
input:nowcoder              # 正确,字符串表达式
>>> type(a)
<class 'str'>             # 字符串

oct():
oct() 函数将一个整数转换成8进制字符串

>>>oct(10)
'012'
>>> oct(20)
'024'
>>> oct(15)
'017'

staticmethod():
python staticmethod 返回函数的静态方法。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class C(object):
    @staticmethod
    def f():
        print('nowcoder');

C.f();          # 静态方法无需实例化
cobj = C()
cobj.f()        # 也可以实例化后调用

nowcoder
nowcoder

bin():
返回一个整数 int 或者长整数 long int 的二进制表示

>>>bin(10)
'0b1010'
>>> bin(20)
'0b10100'

eval():
用来执行一个字符串表达式,并返回表达式的值

>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85

int():
用于将一个字符串或数字转换为整型。

>>>int()               # 不传入参数时,得到结果0
0
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16)        # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制
18
>>> int('0xa',16)  
10  
>>> int('10',8)  
8

open():
Python open() 函数用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。

str():
将对象转化为适于人阅读的形式。

>>>s = 'NOWCODER'
>>> str(s)
'NOWCODER'
>>> dict = {'nowcoder': 'nowcoder.com', 'google': 'google.com'};
>>> str(dict)
"{'google': 'google.com', 'nowcoder': 'nowcoder.com'}"

bool():
用于将给定参数转换为布尔类型,如果没有参数,返回 False。

>>>bool()
False
>>> bool(0)
False
>>> bool(1)
True
>>> bool(2)
True
>>> issubclass(bool, int)  # bool 是 int 子类
True

exec():
exec 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码。

>>>exec('print("Hello World")')
Hello World
# 单行语句字符串
>>> exec("print ('nowcoder.com')")
nowcoder.com

#  多行语句字符串
>>> exec ("""for i in range(5):
...     print ("iter time: %d" % i)
... """)
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4
x = 10
expr = """
z = 30
sum = x + y + z
print(sum)
"""
def func():
    y = 20
    exec(expr)
    exec(expr, {'x': 1, 'y': 2})
    exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})

func()

60
33
34

isinstance():
判断一个对象是否是一个已知的类型
isinstance() 与 type() 区别:
type() 不会认为子类是一种父类类型,不考虑继承关系。
isinstance() 会认为子类是一种父类类型,考虑继承关系。

>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
True
class A:
    pass

class B(A):
    pass

isinstance(A(), A)    # returns True
type(A()) == A        # returns True
isinstance(B(), A)    # returns True
type(B()) == A        # returns False

ord():
ord() 函数是 chr() 函数(对于 8 位的 ASCII 字符串)的配对函数,它以一个字符串(Unicode 字符)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值.

>>>ord('a')
97
>>> ord('€')
8364

sum():
sum() 方法对系列进行求和计算

>>>sum([0,1,2])  
3  
>>> sum((2, 3, 4), 1)        # 元组计算总和后再加 1
10
>>> sum([0,1,2,3,4], 2)      # 列表计算总和后再加 2
12

bytearray():
bytearray() 方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256

>>>bytearray()
bytearray(b'')
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray('nowcoder', 'utf-8')
bytearray(b'nowcoder')

filter():
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

#!/usr/bin/python3

def is_odd(n):
    return n % 2 == 1

tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)

[1, 3, 5, 7, 9]
#!/usr/bin/python3

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0

tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

issubclass():
issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class A:
    pass
class B(A):
    pass

print(issubclass(B,A))    # 返回 True

pow():
pow() 方法返回 x^y(x的y次方) 的值。
pow() 通过内置的方法直接调用,内置方法会把参数作为整型,而 math 模块则会把参数转换为 float。

#!/usr/bin/python3
import math   # 导入 math 模块

print ("math.pow(100, 2) : ", math.pow(100, 2))
# 使用内置,查看输出结果区别
print ("pow(100, 2) : ", pow(100, 2))
print ("math.pow(100, -2) : ", math.pow(100, -2))
print ("math.pow(2, 4) : ", math.pow(2, 4))
print ("math.pow(3, 0) : ", math.pow(3, 0))

math.pow(100, 2) :  10000.0
pow(100, 2) :  10000
math.pow(100, -2) :  0.0001
math.pow(2, 4) :  16.0
math.pow(3, 0) :  1.0

super():
super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print ('Parent')

    def bar(self,message):
        print ("%s from Parent" % message)

class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        super(FooChild,self).__init__()    
        print ('Child')

    def bar(self,message):
        super(FooChild, self).bar(message)
        print ('Child bar fuction')
        print (self.parent)

if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')


Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

bytes():
bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本

>>>a = bytes([1,2,3,4])
>>> a
b'\x01\x02\x03\x04'
>>> type(a)
<class 'bytes'>
>>>
>>> a = bytes('hello','ascii')
>>>
>>> a
b'hello'
>>> type(a)
<class 'bytes'>

float():
float() 函数用于将整数和字符串转换成浮点数。

>>>float(1)
1.0
>>> float(112)
112.0
>>> float(-123.6)
-123.6
>>> float('123')     # 字符串
123.0

iter():
iter() 函数用来生成迭代器。

>>>lst = [1, 2, 3]
>>> for i in iter(lst):
...     print(i)
... 
1
2
3

print():
print() 方法用于打印输出,最常见的一个函数。

>>>print(1)  
1  
>>> print("Hello World")  
Hello World  

>>> a = 1
>>> b = 'nowcoder'
>>> print(a,b)
1 nowcoder

>>> print("aaa""bbb")
aaabbb
>>> print("aaa","bbb")
aaa bbb
>>> 

>>> print("www","nowcoder","com",sep=".")  # 设置间隔符
www.nowcoder.com


import time

print("---NOWCODER EXAMPLE : Loading 效果---")

print("Loading",end = "")
for i in range(20):
    print(".",end = '',flush = True)
    time.sleep(0.5)

tuple():
tuple 函数将列表转换为元组。

>>>list1= ['Google', 'Taobao', 'Nowcoder', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Nowcoder', 'Baidu')

callable():
callable() 函数用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。
对于函数、方法、lambda 函式、 类以及实现了 call 方法的类实例, 它都返回 True。

>>>callable(0)
False
>>> callable("nowcoder")
False

>>> def add(a, b):
...     return a + b
... 
>>> callable(add)             # 函数返回 True
True
>>> class A:                  # 类
...     def method(self):
...             return 0
... 
>>> callable(A)               # 类返回 True
True
>>> a = A()
>>> callable(a)               # 没有实现 __call__, 返回 False
False
>>> class B:
...     def __call__(self):
...             return 0
... 
>>> callable(B)
True
>>> b = B()
>>> callable(b)               # 实现 __call__, 返回 True
True

format():

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'

>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'

>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'
#!/usr/bin/python
# -*- coding: UTF-8 -*-

print("网站名:{name}, 地址 {url}".format(name="牛客教程", url="www.nowcoder.com"))

# 通过字典设置参数
site = {"name": "牛客教程", "url": "www.nowcoder.com"}
print("网站名:{name}, 地址 {url}".format(**site))

# 通过列表索引设置参数
my_list = ['牛客教程', 'www.nowcoder.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的
>>> print("{:.2f}".format(3.1415926));
3.14
#!/usr/bin/python
# -*- coding: UTF-8 -*-

print ("{} 对应的位置是 {{0}}".format("nowcoder"))

nowcoder 对应的位置是 {0}

len():
Python len() 方法返回对象(字符、列表、元组等)长度或项目个数。

>>>str = "nowcoder"
>>> len(str)             # 字符串长度
6
>>> l = [1,2,3,4,5]
>>> len(l)               # 列表元素个数
5

property():
property() 函数的作用是在新式类中返回属性值。
将 property 函数用作装饰器可以很方便的创建只读属性:

class Parrot(object):
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

property 的 getter,setter 和 deleter 方法同样可以用作装饰器:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

type():
type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。

# 一个参数实例
>>> type(1)
<type 'int'>
>>> type('nowcoder')
<type 'str'>
>>> type([2])
<type 'list'>
>>> type({0:'zero'})
<type 'dict'>
>>> x = 1          
>>> type( x ) == int    # 判断类型是否相等
True

# 三个参数
>>> class X(object):
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))  # 产生一个新的类型 X
>>> X
<class '__main__.X'>

chr():
chr() 用一个整数作参数,返回一个对应的字符。

>>>chr(0x30)
'0'
>>> chr(97) 
'a'
>>> chr(8364)
'€'

frozenset():
frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。

>>>a = frozenset(range(10))     # 生成一个新的不可变集合
>>> a
frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = frozenset('nowcoder') 
>>> b
frozenset(['e', 'o', 'w', 'c', 'r', 'd', 'n'])   # 创建不可变集合

list():
list() 方法用于将元组或字符串转换为列表。

#!/usr/bin/python3

aTuple = (123, 'Google', 'Nowcoder', 'Taobao')
list1 = list(aTuple)
print ("列表元素 : ", list1)

str="Hello World"
list2=list(str)
print ("列表元素 : ", list2)

列表元素 :  [123, 'Google', 'Nowcoder', 'Taobao']
列表元素 :  ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

range():
Python3 range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。

>>>range(5)
range(0, 5)
>>> for i in range(5):
...     print(i)
... 
0
1
2
3
4
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(0))
[]

>>>list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 2))
[0, 2, 4, 6, 8]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(1, 0))
[]

vars():
vars() 函数返回对象object的属性和属性值的字典对象。

>>>print(vars())
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> class Nowcoder:
...     a = 1
... 
>>> print(vars(Nowcoder))
{'a': 1, '__module__': '__main__', '__doc__': None}
>>> nowcoder = Nowcoder()
>>> print(vars(nowcoder))
{}

classmethod:
classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class A(object):
    bar = 1
    def func1(self):  
        print ('foo') 
    @classmethod
    def func2(cls):
        print ('func2')
        print (cls.bar)
        cls().func1()   # 调用 foo 方法

A.func2()               # 不需要实例化

func2
1
foo

getattr():
getattr() 函数用于返回一个对象属性值。

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, 'bar')        # 获取属性 bar 值
1
>>> getattr(a, 'bar2')       # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3)    # 属性 bar2 不存在,但设置了默认值
3

locals():
locals() 函数会以字典类型返回当前位置的全部局部变量。

>>>def nowcoder(arg):    # 两个局部变量:arg、z
...     z = 1
...     print (locals())
... 
>>> nowcoder(4)
{'z': 1, 'arg': 4}      # 返回一个名字/值对的字典

repr():
repr() 函数将对象转化为供解释器读取的形式。

>>>s = 'NOWCODER'
>>> repr(s)
"'NOWCODER'"
>>> dict = {'nowcoder': 'nowcoder.com', 'google': 'google.com'};
>>> repr(dict)
"{'google': 'google.com', 'nowcoder': 'nowcoder.com'}"

zip():
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped)  # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c))              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]

>>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]

compile():
compile() 函数将一个字符串编译为字节代码。

>>>str = "for i in range(0,10): print(i)" 
>>> c = compile(str,'','exec')   # 编译为字节代码对象 
>>> c
<code object <module> at 0x10141e0b0, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17

globals():
globals() 函数会以字典类型返回当前位置的全部全局变量。

>>>a='nowcoder'
>>> print(globals()) # globals 函数返回一个全局变量的字典,包括所有导入的变量。
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'a': 'nowcoder', '__package__': None}

map():
map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]

# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

reversed:
reversed 函数返回一个反转的迭代器。

#!/usr/bin/env python3

# 字符串
seqString = 'Nowcoder'
print(list(reversed(seqString)))

# 元组
seqTuple = ('N', 'o', 'w', 'c', 'o', 'd', 'e', 'r')
print(list(reversed(seqTuple)))

# range
seqRange = range(5, 9)
print(list(reversed(seqRange)))

# 列表
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))

['r', 'e', 'd', 'o', 'c', 'w', 'o', 'N']
['r', 'e', 'd', 'o', 'c', 'w', 'o', 'N']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]

import():
import() 函数用于动态加载类和函数 。

如果一个模块经常变化就可以使用 import() 来动态载入。

#!/usr/bin/env python    
#encoding: utf-8  

import os  

print ('在 a.py 文件中 %s' % id(os))

#!/usr/bin/env python    
#encoding: utf-8  

import sys  
__import__('a')        # 导入 a.py 模块

在 a.py 文件中 4394716136

complex():
complex() 函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。。

>>>complex(1, 2)
(1 + 2j)

>>> complex(1)    # 数字
(1 + 0j)

>>> complex("1")  # 当做字符串处理
(1 + 0j)

# 注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
>>> complex("1+2j")
(1 + 2j)

hasattr():
hasattr() 函数用于判断对象是否包含对应的属性。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Coordinate:
    x = 10
    y = -5
    z = 0

point1 = Coordinate() 
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no'))  # 没有该属性

True
True
True
False

max():
max() 方法返回给定参数的最大值,参数可以为序列。

#!/usr/bin/python3

print ("max(80, 100, 1000) : ", max(80, 100, 1000))
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))

max(80, 100, 1000) :  1000
max(-20, 100, 400) :  400
max(-80, -20, -10) :  -10
max(0, 100, -400) :  100

round():
round() 方法返回浮点数x的四舍五入值。

#!/usr/bin/python3

print ("round(70.23456) : ", round(70.23456))
print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))

round(70.23456) :  70
round(56.659,1) :  56.7
round(80.264, 2) :  80.26
round(100.000056, 3) :  100.0
round(-100.000056, 3) :  -100.0

delattr():
delattr 函数用于删除属性。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Coordinate:
    x = 10
    y = -5
    z = 0

point1 = Coordinate() 

print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

delattr(Coordinate, 'z')

print('--删除 z 属性后--')
print('x = ',point1.x)
print('y = ',point1.y)

# 触发错误
print('z = ',point1.z)

('x = ', 10)
('y = ', -5)
('z = ', 0)
--删除 z 属性后--
('x = ', 10)
('y = ', -5)
Traceback (most recent call last):
  File "test.py", line 22, in <module>
    print('z = ',point1.z)
AttributeError: Coordinate instance has no attribute 'z'

hash():
hash() 用于获取取一个对象(字符串或者数值等)的哈希值。

>>>hash('test')            # 字符串
2314058222102390712
>>> hash(1)                 # 数字
1
>>> hash(str([1,2,3]))      # 集合
1335416675971793195
>>> hash(str(sorted({'1':1}))) # 字典
7666464346782421378

memoryview():
memoryview() 函数返回给定参数的内存查看对象(Momory view)。

>>>v = memoryview(bytearray("abcefg", 'utf-8'))
>>> print(v[1])
98
>>> print(v[-1])
103
>>> print(v[1:4])
<memory at 0x10f543a08>
>>> print(v[1:4].tobytes())
b'bce'

set():
set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

>>> x = set('nowcoder')
>>> y = set('google')
>>> x, y
(set(['e', 'o', 'w', 'c', 'r', 'd', 'n']), set(['e', 'o', 'g', 'l']))   # 重复的被删除
>>> x & y         # 交集
set(['e', 'o'])
>>> x | y         # 并集
set(['e', 'l', 'o', 'w', 'c', 'r', 'd', 'g', 'n'])
>>> x - y         # 差集
set(['w', 'c', 'r', 'd', 'n'])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值