python4.3笔记汇总(图片上不去啊)

来源:互联网 发布:淘宝订单取消后果严重 编辑:程序博客网 时间:2024/04/30 23:09

simple_study

版本

3.4.3好些

3.4.3默认utf-8,不用再设置了,而且各种设置,更加的规范。

2.其他

解释器及其环境

错误异常

a=0;
try:
    a==
0
except:
   
print('haha')
else:
   
print('hehe')

用python当计算器

//

>>> 7//2

3

>>> 7//-3

-3

%

>>> 7%2

1

>>> 7%-3

-2

>>> 

虚数

>>> 1j*1j

(-1+0j)

提取实部和虚部:

>>> a=1+2j

>>> a.real

1.0

>>> a.imag

2.0

abs(取模)

>>> a=3+4j

>>> abs(a)

5.0

_

相当于matlab中的ans

>>> 1+1

2

>>> 1 + _

3

3字符串

字符串

特殊字符的引入

>>> 'dosen\'t'

"dosen't"

引号里面的引号

>>> '"Yes",she said'

'"Yes",she said'

\n换行

str='he\nrui'print(str)
结果:
he
rui

 

‘’’来换行

str='''herui'''print(str)
返回:
he
rui 

 

原始

str=r'he\nrui'print(str)
返回:he\nrui

 

+

str1='he'str2='rui'str=str1+str2print(str)
返回:herui

 

*

str1='he'str=str1*4print(str)
返回:hehehehe

切片

str='herui'print(str[3])print(str[0:3])  #3号并不取出来print(str[:2])print(str[2:])
print('_'+str[2:])
print(str[2:100])   #没有意义的就直接省略掉,也就是会自动管理内存
print(str[-2])
返回:
u
her
he
rui
_rui
u

注意:字符串对象是不能修改其中的元素的

列表

可以切片,可以修改,比字符串灵活。

嵌套

a=[1,2]
b=[a
,3]
print(b)

返回; [[1, 2], 3]

len

a=[1,2]
print len(a)

返回:2

 

append

a=[1,2]
a.append(
3)
print(a)

4深入python流程控制

raise

Converts raiseE,V to raiseE(V), and raiseE,V,T to raiseE(V).with_traceback(T). If Eis a tuple, the translation will be incorrect because substituting tuples forexceptions has been removed in 3.0.

print(输出不换行)

print(a,end='')

默认参数值(同c++)

def ask_ok(prompt,retries=4,complaint='Yes or No, Please!'):
   
while True:
        ok=
input(prompt)
       
if okin('y','ye','yes',):
           
return True
       
if okin('n','no','nop','nope'):
           
return False
       
retries=retries-1
       
if retries<0:
           
raise IOError('refusenik user')
       
print(complaint)

关键字参数

ask_ok('yes',complaint='fuck')

必须先写位置参数,然后写关键字参数

引入字典

def fuck(a,b='herui',*c):
   
print(a,"authoris",b,*c)
print(fuck('hehe','ruirui','hehe','hehehe'))

返回:hehe author isruirui hehe hehehe

 

引入一个形如 **name 的参数时,它接收一个字典(参见 typesmapping ) ,该字典包含了所有未出现在形式参数列表中的关键字参数。这里可能还会组合使用一个形如 *name (下一小节詳細介绍) 的形式参数,它接收一个元组(下一节中会详细介绍),包含了所有没有出现在形式参数列表中的参数值。( *name 必须在 **name 之前出现) 例如,我们这样定义一个函数:

defcheeseshop(kind,*arguments,**keywords):

    print("--Do you have any",kind,"?")

    print("--I'm sorry, we're all out of",kind)

    for argin arguments:

       print(arg)

    print("-"*40)

   keys =sorted(keywords.keys())

    for kwin keys:

       print(kw,":", keywords[kw])

它可以像这样调用:

cheeseshop("Limburger","It'svery runny, sir.",

          "It's reallyvery, VERY runny, sir.",

          shopkeeper="Michael Palin",

          client="John Cleese",

          sketch="Cheese Shop Sketch")

当然它会按如下内容打印:

-- Do you have any Limburger ?

-- I'm sorry, we're all out of Limburger

It's very runny, sir.

It's really very, VERY runny, sir.

----------------------------------------

client : John Cleese

shopkeeper : Michael Palin

sketch : Cheese Shop Sketch

可变参数列表(3以后版本支持)

>>> defconcat(*args, sep="/"):

...    return sep.join(args)

...

>>> concat("earth","mars","venus")

'earth/mars/venus'

>>> concat("earth","mars","venus", sep=".")

'earth.mars.venus'

2.7.11就是不支持有arg了,再有sep,日了狗了,c++也支持啊。

3.4.3支持

参数列表的分拆

defparrot(voltage, state='astiff', action='voom'):

...     print("--This parrot wouldn't",action, end=' ')

...     print("ifyou put", voltage, "volts through it.", end=' ')

...     print("E's", state, "!")

...

>>> d= {"voltage":"four million","state":"bleedin' demised","action":"VOOM"}

>>> parrot(**d)

-- This parrot wouldn't VOOM if you putfour million volts through it. E's bleedin' demised !

其实也是引入字典

def fuck(a='1',b='2'):
   
return a+b
d={
'a':'3','b':'4'}
print(fuck(**d))

返回:34

注释风格:

'''do nothing,but document it

no, it really do nothing
'''

第一行,与后面的行分开一行

编码风格:

折行以确保其不会超过 79 个字符。

这有助于小显示器用户阅读,也可以让大显示器能并排显示几个代码文件。

把空格放到操作符两边,以及逗号后面,但是括号里侧不加空格: a = f(1, 2) + g(3, 4) 。

注释英文,国际化,没必要吧.

5.数据结构

列表:

append

list=[1,2,3]
list.append(
4)
print(list)

返回:[1, 2, 3, 4]

extend

list=[1,2,3]
list1=[
4,5,6]
list.extend(list1)
print(list)

返回:[1, 2, 3, 4, 5, 6]

insert

list=[1,2,3]
list.insert(
2,0)
print(list)

返回:[1, 2, 0, 3]

remove

list=[1,2,3]
list.remove(
2)
print(list)

返回:[1, 3]

pop

list=[1,2,3]
list.pop()
print(list)

返回:[1, 2]

index

list=[1,2,3]
a=list.index(
2)
print(a)

返回:1 #list中值为2的索引是1

 

count

list=[1,2,3,2]
a=list.count(
2)
print(a)

返回:2

sort

list=[1,2,3,2]
list.sort()
print(list)

返回:[1, 2, 2, 3]

list=[1,2,3,2]
list.reverse()
print(list)

返回:[2, 3, 2, 1]

实现栈

append和pop简直就是栈

list_stack=[1,2,3]
list_stack.append(
4)
list_stack.pop()
print(list_stack)

返回:[1, 2, 3]

 

实现队列

要导入deque模块

from collectionsimportdeque
queue=deque([
1,2,3])
queue.append(
4)
queue.popleft()
print(queue)

返回:deque([2, 3, 4])

详细(8.3.3)

列表推倒式

list=[x**2forxinrange(10)]
print(list)

返回:[0, 1, 4, 9, 16, 25,36, 49, 64, 81]

代替了:

list=[]
for xinrange(10):
    list.append(x**
2)
print(list)

很明显第一种表示更简洁易懂。

列表推导式由包含一个表达式的括号组成,表达式后面跟随一个 for 子句,之后可以有零或多个 for 或 if 子句。 结果是一个列表,由表达式依据其后面的 for 和 if 子句上下文计算而来的结果构成

值得注意的是在上面两个方法中的 for  if 语句的顺序

1.

list=[(x,y)forxin[1,2,3]foryin[1,2,3]ifx != y]
print(list)

返回:[(1, 2), (1, 3), (2,1), (2, 3), (3, 1), (3, 2)]

 

2.

list=[]
for xin[1,2,3]:
   
for yin[1,2,3]:
       
if x !=y:
            list.append((x
,y))
print(list)

返回:[(1, 2), (1, 3), (2,1), (2, 3), (3, 1), (3, 2)]

很明显,1比2简单。

pi模块

from mathimportpi
a = [
str(round(pi,i))foriinrange(1,6)]
print(a)

返回:['3.1', '3.14','3.142', '3.1416', '3.14159']

嵌套的列表推倒式

matrix=[[1,2],[3,4]]

a=[[row[i]forrowinmatrix]foriinrange(2)]
print (a)

返回:[[1, 3], [2, 4]]

等效:

matrix=[[1,2],[3,4]]
a=[]
for iinrange(2):
   
for rowinmatrix:
        a.append(row[i])

很明显第一种表达式好看了不少 。。

zip函数

详细

a=[[1,2],[3,4]]
b=
list(zip(*a))
print(b)

返回:[(1, 3), (2, 4)]

两维以上

a)=[[1,[4,5]],[3]]
b=
list(zip(*a))
print(b)

返回:[(1, 3)]

下一个:

a=[[1,[4,5]],[3,2]]
b=
list(zip(*a))
print(b)

返回:[(1, 3), ([4, 5],2)]

所以:不管有几维zip只处理前两维

del语句

a=[1,2,3]
del a[0:2]
print(a)

返回:[3]

元祖和序列

a = ()
b = (
1,)
print(len(a),end=',')
print(len(b))

返回:0,1

注意b中的逗号。。。

集合

a =set('abcdefg')
b =
set('abchi')
print(a - b)
print(a & b)
print(a | b)
print(a ^ b)

返回:

{'d', 'f', 'g','e'}

{'b', 'a', 'c'}

{'d', 'f', 'i','b', 'g', 'h', 'e', 'a', 'c'}

{'d', 'f', 'i','g', 'h', 'e'}

注意集合与列表的区别(用set生成,如果用大括号生成就没有这个运算了)

 字典

a = {'n1':1,'n2':2,'n3':3}
a[
'n4'] =4
print(sorted(a))
del a['n2']
print(a)
print(list(a.keys()))
print(list(a.values()))

返回:

['n1', 'n2', 'n3','n4']

{'n4': 4, 'n3': 3,'n1': 1}

['n4', 'n3', 'n1']

[4, 3, 1]

dict构造

a =dict([('n1',1),('n2',2)])
print(a)

返回:{'n1': 1, 'n2': 2}

另一种方式

a =dict(n1=1,n2=2)
print(a)

字典推导式

a = {x: x**xforxinrange(2,4)}
print(a)

循环技巧

字典中items()

a =dict(n1=1,n2=2)
for k,vina.items():
   
print(k,v)

返回:

n2 2

n1 1

序列中enumerate()

a=[1,2,3]
for k,vinenumerate(a):
   
print(k,v)

返回:

0 1

1 2

2 3

注意:enumerate()不是类方法,而是独立的函数,list中没有这个类型

zip打包

a = [1,2]
b = [
4, 5]
for k,vinzip(a,b):
   
print(k,v)

返回:

1 4

2 5

zip不止能倒置,还能打包。吼吼。。

reversed

for iinreversed(range(1,10,2)):
   
print(i,end=',')

返回:9,7,5,3,1,

sorted

老熟人了

深入条件控制

and or

a=0
b=2
c=aorb
print(c)

返回:2

注意:如果是c则会复制c True,但是在python中不能这样。

需要注意的是 Python 与 C 不同,在表达式内部不能赋值。C 程序员经常对此抱怨,不过它避免了一类在 C 程序中司空见惯的错误:想要在解析式中使== 时误用了 = 操作符。

比较序列和其他类型

(1,2,3)             < (1,2,4)

[1,2,3]             < [1,2,4]

'ABC'<'C'<'Pascal'<'Python'

(1,2,3,4)          < (1,2,4)

(1,2)                < (1,2,-1)

(1,2,3)            == (1.0,2.0,3.0)

(1,2, ('aa','ab'))  < (1,2, ('abc','a'),4)

 

6模块

脚本概念

如果你退出 Python 解释器并重新进入,你做的任何定义(变量和方法)都会丢失。 因此,如果你想要编写一些更大的程序,为准备解释器输入使用一个文本编辑器会更好,并以那个文件替代作为输入执行。 这就是传说中的 脚本 。 

简单一个例子

当前目录下创建一个txt1.py文件

def fuck():
   
print('fuck')

另外一个文件引用:

import txt1
txt1.fuck()

返回:fuck

返回模块名:

print(txt1.__name__)

不知道他要干什么,哈哈。。

频繁使用

import txt1
fuck = txt1.fuck
fuck()

这样应该是能提高效率(因该是相当于在本文件给复制了这个函数,所以快了)

深入模块

导入部分

from txt1importfuck
fuck()

这样可以导入所有除了以下划线开头命名的模块

将模块作为脚本执行

(不懂啊)

6.1.2. 模块的搜索路径

导入一个叫 spam 的模块时,解释器先在当前目录中搜索名为 spam.py 的文件。如果没有找到的话,接着会到 sys.path 变量中给出的目录列表中查找。sys.path 变量的初始值来自如下:

  • 输入脚本的目录(当前目录。
  • 环境变量 PYTHONPATH 表示的目录列表中搜索 (这和 shell 变量 PATH 具有一样的语法,即一系列目录名的列表)。
  • Python 默认安装路径中搜索。

实际上,解释器由 sys.path 变量指定的路径目录搜索模块,该变量初始化时默认包含了输入脚本(或者当前目录), PYTHONPATH 和安装目录。这样就允许 Python 程序了解如何修改或替换模块搜索目录。需要注意的是由于这些目录中包含有搜索路径中运行的脚本,所以这些脚本不应该和标准模块重名,否则在导入模块时 Python 会尝试把这些脚本当作模块来加载。这通常会引发错误。请参见 标准模块 以了解更多的信息。

增加搜索路径

importsys

>>> sys.path.append('/ufs/guido/lib/python')

dir罗列目录

import txt1
print(dir(txt1))

返回:

['__builtins__','__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__','__spec__', 'fuck']

无参数调用时, dir() 函数返回当前定义的命名:

import txt1
rs=
dir()
print(rs)

返回同上

包含__init__

7.格式化输出

格式化输出

repr(object)

Return a stringcontaining a printable representation of an object. For many types, thisfunction makes an attempt to return a string that would yield an object withthe same value when passed toeval(), otherwise the representation is a string enclosed inangle brackets that contains the name of the type of the object together withadditional information often including the name and address of the object. Aclass can control what this function returns for its instances by defining a __repr__() method.

就是返回字符串的。。

str.rjust

for ninrange(1,11):
   
print(repr(n).rjust(2),repr(n*n).rjust(3),end=' ')
   
print(repr(n*n*n).rjust(4))

返回:

1   1 1

 2   4 8

 3   9 27

 4  16 64

 5  25125

 6  36216

 7  49343

 8  64512

 9  81729

10 100 1000

str.zfill

rs ='12'.zfill(5)
print(rs)

返回:00012

str.format

for ninrange(1,11):
   
print('{0: 2d} {0: 3d} {0: 4d}'.format(n,n*n,n*n*n))

 

print('{}is me, {}'.format('herui','haha'))

括号中的数值指明使用传入 str.format() 方法的对象中的哪一个。:

print('{1}is me, {0}'.format('herui','haha'))

返回:haha is me, herui

关键字:

print('{name}is me, {saysomething}'.format(name='herui',saysomething='haha'))

'!a' (应用 ascii()), '!s' (应用 str() ) 和 '!r' (应用 repr() ) 可以在格式化之前转换值:

print('{!a}'.format('a'))
print(
'{!r}'.format('a'))
print(
'{!s}'.format('a'))

字段名后允许可选的 ':' 和格式指令。这允许对值的格式化加以更深入的控制。下例将Pi 转为三位精度。

import math
print('{0:.3f}'.format(math.pi))

返回:3.142

在字段后的 ':' 后面加一个整数会限定该字段的最小宽度,这在美化表格时很有用

str={'abc':'def','ghi':'jkl'}
for keys,valuesinstr.items():
   
print('{0:8} == > {0:80}'.format(keys,values))
返回:

abc      == > abc                                                                            

ghi      == > ghi

与字典的配合使用

str={'abc':'def','ghi':'jkl'}
print('abc{abc}; ghi {ghi}'.format(**str))

返回:abc def; ghi jkl

文件读写

函数 open() 返回文件对象,通常的用法需要两个参数: open(filename, mode)。f = open('herui.txt','w')

第一个参数是一个标识文件名的字符串。第二个参数是由有限的字母组成的字符串,描述了文件将会被如何使用。可选的 模式 有: 'r' ,此选项使文件只读; 'w' ,此选项使文件只写(对于同名文件,该操作使原有文件被覆盖); 'a' ,此选项以追加方式打开文件; 'r+' ,此选项以读写方式打开文件; 模式 参数是可选的。如果没有指定,默认为 'r' 模式。

在 Windows 平台上, 'b' 模式以二进制方式打开文件,所以可能会有类似于 'rb' , 'wb' , 'r+b' 等等模式组合。Windows 平台上文本文件与二进制文件是有区别的,读写文本文件时,行尾会自动添加行结束符。这种后台操作方式对 ASCII 文本文件没有什么问题,但是操作 JPEG 或 EXE 这样的二进制文件时就会产生破坏。在操作这些文件时一定要记得以二进制模式打开。在 Unix 上,加一个 'b' 模式也一样是无害的,所以你可以一切二进制文件处理中平台无关的使用它。

文件读写

读一行

f =open('herui.txt')
rs = f.readline()
print(rs)

读全文

f = open('herui.txt')
rs = f.read()
print(rs)

读多行

f =open('herui.txt')
rs = f.readlines()
print(rs)

返回:

['haha\n', '\n','\n', 'herui']

读写模式下进行写

f = open('herui.txt','r+')f.write('herui shi wo')rs = f.readlines()print(rs)f.close()

返回:['herui shi wo']

注意到没有,返回的是元祖啊。。。为什么呢?

 

用关键字 with 处理文件对象是个好习惯。它的先进之处在于文件用完后会自动关闭,就算发生异常也没关系。它是 try-finally 块的简写:

with open('herui.txt')asf:
    rs = f.read()
   
print(rs)
is_closed = f.closed
print(is_closed)

返回:

herui shi woheruishi wo

True

屌不屌,以后就用with了呗。。。

pickle模块(并没有搞懂)

我们可以很容易的读写文件中的字符串。数值就要多费点儿周折,因为 read() 方法只会返回字符串,应该将其传入 int() 这样的方法中,就可以将'123' 这样的字符转为对应的数值 123。不过,当你需要保存更为复杂的数据类型,例如列表、字典,类的实例,事情就会变得更复杂了。

好在用户不必要非得自己编写和调试保存复杂数据类型的代码。 Python 提供了一个名为 pickle 的标准模块。这是一个令人赞叹的模块,几乎可以把任何 Python 对象 (甚至是一些 Python 代码段!)表达为为字符串,这一过程称之为封装 ( pickling )。从字符串表达出重新构造对象称之为拆封(unpickling )。封装状态中的对象可以存储在文件或对象中,也可以通过网络在远程的机器之间传输。

如果你有一个对象 x ,一个以写模式打开的文件对象 f ,封装对象的最简单的方法只需要一行代码:

pickle.dump(x,f)

如果 f 是一个以读模式打开的文件对象,就可以重装拆封这个对象:

x = pickle.load(f)

(如果不想把封装的数据写入文件,这里还有一些其它的变化可用。完整的 pickle 文档请见Python 库参考手册)。

pickle 是存储 Python 对象以供其它程序或其本身以后调用的标准方法。提供这一组技术的是一个 持久化 对象( persistent object )。因为 pickle的用途很广泛,很多 Python 扩展的作者都非常注意类似矩阵这样的新数据类型是否适合封装和拆封。

8.错误和异常

try

try

except

raise

raise抛出异常

def scope_test():
   
def do_local():
       
spam ='local span'
   
def do_nonlocal():
       
nonlocal spam
        spam =
'nonlocal spam'
   
def do_global():
       
global spam
        spam =
'global spam'

   
spam = 'testspam'
   
do_local()
   
print(spam)
    do_nonlocal()
   
print(spam)
    do_global()
   
print(spam)

scope_test()
print(spam)

返回:

test spam

nonlocal spam

nonlocal spam

global spam

local 赋值语句是无法改变 scope_test 的 spam 绑定。 nonlocal 赋值语句改变了 scope_test 的 spam 绑定,并且 global 赋值语句从模块级改变了 spam 绑定。

 

初始类:

class MyClass:
    i =
123
   
def f(self):
       
return 'hello,world'

x = MyClass()
print(x.i)
print(x.f())

 

函数定义在外面

def f1(self,x, y):
   
return min(x,x+y)
class C:
    f = f1
   
def g(self):
       
return 'hello,world'
   
h = g

obj = C()
rs = obj.g()
print(rs)

 

构造函数

class Bag:
   
def __init__(self):
       
self.data= []
   
def add(self,x):
       
self.data.append(x)
   
def addtwice(self,x):
       
self.data.append(x)
       
self.data.append(x)

继承

class cls1:
    a =
1
class cls2(cls1):
    b =
2

obj1 = cls1()
obj2 = cls2()
print(obj2.a)

多继承就是在括号里多写两个

class cls1:
    __a =
1
   
def __fuck():
       
print('hello, fuck you!')
class cls2(cls1):
    b =
2
obj = cls2()

补充

class cls1:
   
pass

obj = cls1()
obj.str =
'abc'
print(obj.str)

异常也是类

class B(Exception):
   
pass
class
C
(B):
   
pass
class
D
(B):
   
pass

for
cls in[B,C,D]:
   
try:
       
raise cls()
   
except D:
       
print('D')
   
except C:
       
print('C')
   
except B:
       
print('B')
   
else:
       
print('fuck!')

迭代器

str ='he'
it = iter(str)
print(next(it))
print(next(it))

返回:

h

e

 

class cls1:
   
def __init__(self,data):
       
self.data= data
       
self.index=len(data)
   
def __iter__(self):
       
return self
   
def __next__(self):
       
if self.index ==0:
           
raise  StopIteration
       
self.index=self.index -1
       
return self.data[self.index]

obj = cls1(
'herui')
print(obj.data[0])
print(obj.__next__())

 

python标准库概览

略,自己读英文文档,标准库的。

 

 

 

 

 

 

 

 

 

 

 

 


 

python codebook

字符串基础

写字符串

多行扩展来写同一行字符串

 

 

 

 


特殊符号的使用,用反斜杠

 

 

 

 

 


使用’’’符号

 

 

 

 

 

 

 

 


加r (忽视反斜杠)

word=r'herui\nhaha'

 

访问字符串

索引

word=r'herui\nhaha'print(word[-2])

 

切片

print(word[1:4])

返回:

eru

发现这里没有包含4了么?

print(word[1:8:2])

第三个参数是步长

循环遍历

for c in word:   print(c)

注意循环有冒号,恶心不恶心。。。

 

 

类函数

isdigit

是否字符串中的全是数字

str='1234'
print(str.isdigit())

返回:false

splitlines

切片,形成元组

str='herui\nhaha'

str_split=str.splitlines()
print(str_split)

返回 ['herui', 'haha']

join

把切片的在组合起来

str='herui\nhaha'
str_split=str.splitlines()
str_new=
'\n'.join(str_split)
print(str_new)

返回:herui\nhaha

count

搜索字符串中有多少个””

str='he he he ha ha'
print(str.count('he'))

返回:3

upper

小写转换为大写

str='he he he ha ha'
print(str.upper())

返回:HE HE HE HA HA

lower

单独函数

list

将字符串拆开

str='he he he ha ha'
str_list=list(str)
print(str_list)

返回:['h', 'e', ' ', 'h','e', ' ', 'h', 'e', ' ', 'h', 'a', ' ', 'h', 'a']

map

映射

ls=[1,2,3]
def add(num):
   
return num+1
rs=map(add,ls)
print(rs)

返回:[2, 3, 4]

1.1每次处理一个字符

for语句

list函数

map函数

1.2字符与字符值之间的转换

ord函数
chr()的逆

ord(c)

Given a stringrepresenting one Unicode character, return an integer representing the Unicodecode point of that character. For example, ord('a') returns the integer 97 andord('\u2020') returns 8224. This is the inverse of chr().

a=ord('a')
print(a)

返回:97

repr

什么鬼?有待考察

repr(object)

Return a stringcontaining a printable representation of an object. For many types, thisfunction makes an attempt to return a string that would yield an object withthe same value when passed toeval(), otherwise the representation is a string enclosed inangle brackets that contains the name of the type of the object together withadditional information often including the name and address of the object. Aclass can control what this function returns for its instances by defining a __repr__() method.

chr与str

a=97
print(str(a))
print(chr(a))

返回:

97

a

测试一个对象是否是字符串

a='123'
rs=isinstance(a,basestring)
print(rs)

返回:true

 

instrance内建函数

isinstance(object,classinfo)

Return true if theobject argument is an instance of theclassinfo argument, or of a(direct, indirect orvirtual)subclass thereof. Ifobject is not an object of the given type, thefunction always returns false. Ifclassinfo is not a class (typeobject), it may be a tuple of type objects, or may recursively contain othersuch tuples (other sequence types are not accepted). Ifclassinfo is nota type or tuple of types and such tuples, a TypeError exception is raised.

这个函数很快。

字符串对对齐

ljust左对齐补充

print 'abc'.ljust(4,'*'),'b'

返回:abc* b

str.ljust(width[,fillchar])

Return the stringleft justified in a string of lengthwidth. Padding is done using thespecifiedfillchar (default is a space). The original string is returnedifwidth is less than or equal to len(s).

rjust

center

去除字符串两端的空格

lstrip

rstrip

strip

str.lstrip([chars])

Return a copy ofthe string with leading characters removed. Thechars argument is astring specifying the set of characters to be removed. If omitted or None, thecharsargument defaults to removing whitespace. The chars argument is not aprefix; rather, all combinations of its values are stripped:

>>>'   spacious   '.lstrip()

'spacious   '

>>> 'www.example.com'.lstrip('cmowz.')

'example.com'

合并字符串

join

join()

Block until allitems in the queue have been gotten and processed.

The count ofunfinished tasks goes up whenever an item is added to the queue. The count goesdown whenever a consumer thread callstask_done() to indicate that theitem was retrieved and all work on it is complete. When the count of unfinishedtasks drops to zero,join() unblocks.

This method is a coroutine.

%

a='a'
b='b'
str='%s and %s is my print'%(a,b)
print(str)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

python技术手册

面向对象的python

类和实例

类私有变量

__双下划线开头但是不以双下划线结束的变量或函数,表示私有变量。

相当于构造函数功能

class cls:
  
def __init__(self,n):
      
self.x =n

 

__init__本身是类有的,比如

class cls:    passobj = cls()print(cls.__name__)print(obj.__name__)

也就是说双下滑线是类所拥有的,但是对象并不拥有,如果要使对象拥有,可以通过def 函数给定义给。

class cls:   def __init__(self, n):       self.x = nobj = cls(6)print(obj.x)

工厂函数

class normal(object):    def amethod(self):        print('normal')class special(object):    def amethod(self):        print('special')def approriate(isnormal = True):    if isnormal:        return normal()    else:        return special()aninstance = approriate(False)aninstance.amethod()

继承

class cls(object):    a = 1    b = 2    def f(self):        print('method f in class cls')    def g(self):        print('method g in class cls')class cls2(cls):    b = 3    c = 4    d = 5    def g(self):        print('methond g in cls2')    def g(self):        print('method f in cls2')x = cls2()print(x.b)

看出来什么?竟然把基类的数据改变了

太可怕了,把封装性给没了

class cls:    a = 1class cls2(cls):    a = 2    cls.a = 3print(cls.a)print(cls2.a)

基类寻找顺序

class cls:    def amethod(self):        print('cls')class cls2(cls):    passclass cls3:    def amethod(self):        print('cls3')class cls4(cls2, cls3):    passaninstance = cls4()aninstance.amethod()

还记得树的从左到右的寻找顺序么,是的,这个就是这样。。

cls4没找到,就找cls2也没有找到,找cls找到了,over

在子类中用父类的重名函数

class cls:    def fuck(self, name):        print('welcome', name)class cls2(cls):    def fuck(self, name):        print('well met at')        cls.fuck(self, name)obj = cls2()obj.fuck('herui')

好危险,基类属性被删除了

class cls:    def __init__(self):        anattribute = 1class cls2(cls):     def __init__(self):         cls.anattribute = 2obj = cls()rs = obj.anattributeprint(rs)

返回错误,也就是说cls中没有anattribute这个属性了,,,

 

一些想法:

Python的类也太危险了吧:class cls:    a = 1class cls2(cls):    a = 2    cls.a = 3class cls3(cls):    a = 5    cls.a = 4print(cls2.a)

看吧,cls2把cls的a数据改为3, 继而 cls3 又把cls的a数据改为4,最后cls.a 为4,这个就取决于谁先被编译,,,如果没看到cls3看到了cls2使用cls.a那不就得跪么。

方法执行顺序

class cls:    def fuck(self):        print('cls')class cls2(cls):    def fuck(self):        print('cls2')        cls.fuck(self)class cls3(cls):    def fuck(self):        print('cls3')        cls.fuck(self)class cls4(cls2, cls3):    def fuck(self):        print('cls4')        cls2.fuck(self)        cls3.fuck(self)obj = cls4()obj.fuck()

合作超类(保证祖先的方法只执行一次)

 

 

 

 

 

tkinter

tkinter

import tkintertop = tkinter.Tk()top.mainloop()

注意3以上版本都编程了tkinter不是Tkinter了

hello,world程序

import tkinter as tkclass Application(tk.Frame):    def __init__(self, master=None):        tk.Frame.__init__(self, master)        self.pack()        self.createWidgets()    def createWidgets(self):        self.hi_there = tk.Button(self)        self.hi_there["text"] = "Hello World\n(click me)"        self.hi_there["command"] = self.say_hi        self.hi_there.pack(side="top")        self.QUIT = tk.Button(self, text="QUIT", fg="red",                                            command=root.destroy)        self.QUIT.pack(side="bottom")    def say_hi(self):        print("hi there, everyone!") root = tk.Tk()app = Application(master=root)app.mainloop()

比起c++来说简单了不少额。。

 

标签

from tkinter import *root = Tk()root.title('hello, world')root.geometry('300x200')root.resizable(width=False, height=True)l = Label(root, text='show', bg='green', font=('Arial', 12), width = 5, height = 2)l.pack(side = LEFT)root.mainloop()

标签2

 

from tkinter import *root = Tk()root.title('herui')root.geometry('300x200')#root.resizable(width = False, height = True)Label(root, text = '0', font = ('Arial', 12)).pack()frm = Frame(root)frm_L = Frame(frm)Label(frm_L, text = '1', font = ('Arial', 12)).pack(side = TOP)Label(frm_L, text = '2', font = ('Arial', 12)).pack(side = TOP)frm_L.pack(side = LEFT)frm_R = Frame(frm)Label(frm_R, text = '3', font = ('Arial', 12)).pack(side = TOP)Label(frm_R, text = '4', font = ('Arial', 12    )).pack(side = TOP)frm_R.pack(side = RIGHT)frm.pack()root.mainloop()

root是tk层

frm是一个框架 ß  root

frm_L frm_R  ß  frm

布局评价:这样还好,但是理想中布局应该项div+css这样的。。

也许后面会有改善。。

文本框

from tkinter import *root = Tk()root.geometry('300x200')var = StringVar()e = Entry(root, textvariable = var)var.set('hello')e.pack()root.mainloop()

文本框,建议:尽量给写的控件都命名比较好。

当然为了防止名称冲入也可以不命名。写的少就尽量命名。

控件对于父类依靠,,注意层层之间的关系。

Text编辑框

from tkinter import *root = Tk()root.title('herui')root.geometry('300x200')t = Text(root)t.insert(1.0, 'hello,world\n')t.insert(END, 'hello,world\n')t.insert(END, 'hello,world')t.pack()root.mainloop()

 

按钮

from tkinter import *root = Tk()root.title('herui')root.geometry('300x200')def print_hello():    t.insert('1.0', 'hello\n')t = Text(root)t.pack()b= Button(root, text = 'press', command = print_hello )b.pack()root.mainloop()

 

列表

from tkinter import *root = Tk()root.title('herui')root.geometry('300x200')def print_item(event):    print(lb.get(lb.curselection()))var = StringVar()lb = Listbox(root, listvariable = var)list_item = [1, 2, 3, 4]for item in list_item:    lb.insert(END, item)lb.delete(0, 2) #删除编号为0 至 2#var.set(('a', 'b', 'c', 'd'))print(var.get())lb.pack()root.mainloop()

图片

from tkinter import *root = Tk()class App():    def __init__(self, master):        frame = Frame(master)        frame.pack()        theLabel = Label(frame,                         textvariable = '未满18岁不得进入',                         font = ('Arial', 12),                         fg = 'black')                         #image = photo)        frame.pack()        theLabel.pack()photo = PhotoImage('haha.jpg')app = App(root)root.mainloop()

注意:这段代码嵌不进去图片,而且textvariable没法嵌入,text可以,真神奇

测试选框

from tkinter import *root = Tk()v = IntVar()c = Checkbutton(root,                text = 'test',                variable = v)c.pack()c = Label(root, textvariable = v)c.pack()root.mainloop()
 
#anchor是对齐方式,向西对齐
Checkbutton(root, text = 'herui', variable = v[0]).pack(anchor = W)
 

模块

from tkinter import *root = Tk()v = IntVar()v.set(1)print(v.get())root.mainloop()

注意:IntVar是tkinter模块里定义的。

v.get:返回这个操作模块

v.get():返回这个操作后的值

from tkinter import *root = Tk()v = []for n in range(1, 5):    v.append(IntVar())    print(v[n - 1])root.mainloop()

这个IntVar()可以自动给赋值,0,1,2,3,,,

 

LabelFrame和Radiobutton

from tkinter import *root = Tk()root.title('herui')group = LabelFrame(root, text = 'chose', padx = 5, pady = 5)group.pack(padx = 10, pady = 10)GIRLS = [('first', 1),         ('second', 2),         ('thrid', 3),         ('fourth', 4)]for girl, num in GIRLS:    b = Radiobutton(group, text = girl, variable = num, )    b.pack(anchor = W)root.mainloop()

有问题:

四个竟然都选了。

计算器

from tkinter import *root = Tk()v1 = StringVar()v2 = StringVar()v3 = StringVar()def add():    result = int(v1.get()) + int(v2.get())    v3.set(result)frame = Frame(root)frame.pack(padx = 10, pady =10)e1 = Entry(frame, textvariable = v1, width = 10).grid(row = 0, column = 0)label1 = Label(frame, text = '+').grid(row = 0, column = 1)e2 = Entry(frame, textvariable = v2, width = 10).grid(row = 0, column = 2)label2 = Label(frame, text = '=').grid(row = 0, column = 3)e3 = Entry(frame, textvariable = v3, width = 10,state = 'readonly').grid(row = 0, column = 4)calculate = Button(frame, text = 'calculate', command = add).grid(row = 1, column = 2)root.mainloop()

但是,这个没有弄成功检测程序,安全性非常低

列表2

from tkinter import *root = Tk()theList = Listbox(root)HEHE = [1, 2, 3, 4]for n in HEHE:    theList.insert(END, n)theList.pack()cmd = Button(root, text = 'delete', command = lambda x=theList : x.delete(ACTIVE))cmd.pack()root.mainloop()

注意,cmd = Button(root, text = ‘delete’,command = theList.delete(ACTIVE))则只会删除1,因为这时它给的不是一种方法,而是一个固定操作

其实我也不是很清楚

lambda函数

lambda函数和def函数:

lambda函数也叫匿名函数,就是没有名字的函数

lambda只是一个表达式,而def是语句。lambda有时能简化代码。

sum = lambda x, y=10: x+yprint(sum(1))

发现也没有简化多少是不

熟悉手册

说明:

总的来说,这个手册已经够我们使用了。另外补充部分我们会在后面写出

英文单词

widget 控件

滚动条

from tkinter import *root = Tk()sb = Scrollbar(root)sb.pack(side = RIGHT, fill = Y)lb = Listbox(root, yscrollcommand = sb.set, height = 10)for i in range(1,1000):    lb.insert(END, i)lb.pack(side = LEFT, fill = BOTH)sb.config(command = lb.yview) #这条语句把滚动条和列表建立关系root.mainloop()

 

from tkinter import *root = Tk()scroll1 = Scale(root, from_ = 0, to = 100, tickinterval = 20, resolution = 20)scroll1.pack()scroll2 = Scale(root, from_ = 0, to = 100, tickinterval = 20, resolution = 20, orient = HORIZONTAL)scroll2.pack()root.mainloop()

text

from tkinter import *root = Tk()text = Text(root, width = 30, height = 5)text.pack()for n in range(1,6):    text.insert(END, n)    text.insert(END, '\n')root.mainloop()

一些样式修改:

from tkinter import *root = Tk()text = Text(root, width = 30, height = 5)text.pack()for n in range(111,116):    text.insert(END, n)    text.insert(END, '\n')text.tag_add('tag1', '1.0', '1.2')text.tag_config('tag1', foreground = 'red', background = 'yellow')root.mainloop()

画布

from tkinter import *root = Tk()w = Canvas(root, width = 200, height = 100)w.pack()w.create_line(0, 0, 200, 100, fill = 'red', width = 3)w.create_line(200, 0, 0, 100, fill = 'red', width = 3)w.create_rectangle(40, 20, 160, 80, fill = 'green')w.create_rectangle(65, 35, 135, 65, fill = 'yellow')w.create_text(100, 50,text 'herui')root.mainloop()

 

五角星

from tkinter import *import math as mroot = Tk()##########w = Canvas(root, width = 200, height = 200)w.pack()x_center = 100y_center = 100x = []y = []l = 50######################def init_point():    for n in range(0, 5):        x.append(x_center + l * m.cos(m.pi / 2.5 * n + m.pi / 2))        y.append(y_center - l * m.sin(m.pi / 2.5 * n + m.pi / 2))def create_canvas():    #这两组增加为了画图方便,后面记得删除    x.append(x[0])    y.append(y[0])    x.append(x[1])    y.append(y[1])    for n in range(0, 5):        #print(x[n], y[n])    #测试点        w.create_line(x_center, y_center, x[n], y[n])        w.create_line(x[n], y[n], x[n+2], y[n+2])    #记住了,我给删除掉了    del x[5:]    del y[5:]    #print(x[n]); print(y[n])  #检测是否删除######################init_point()create_canvas()#################root.mainloop()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1 0