python程序执行
- python是解释性语言,不需要先编译成二进制语言。
- python不需要main函数也能执行。
- 顺序执行
test()函数在main()上方,则先执行的是test函数 - __name__是系统内置变量,代表所在模块名字,也即所在文件名。
- if __name__ == '__main__'
当.py文件被直接执行时,该代码后的代码将被执行;
当.py文件被作为模块导入时,改代码后的代码不被执行。 - python中的def如果不被调用,就不会被执行。
——————————————————————————————————————————
python的七个标准数据类型
Bool(布尔):
True和False
Number(数字)[不可变数据]:
分为int(整数)、long(长整数)、float(浮点数)、complex(复数)
默认17位小数精度,即小数点后16位是准确的。
String(字符串)[不可变数据]:
转义符 " \ "引入r可不转义:
print(r"\\\\t\\") # \\\t\\
Tuple(元组)[不可变数据]:
与列表相似,但元组内的元素不可修改/删除,但可以将整个元组删除。
创建元组:
tup1=() ##空元组
tup2=(30,) ##只含一个元素需要加逗号
List(列表):
创建列表:
list0 = ['hello', 'world', 1111, 2222]
list1 = [1, 2, 3, 4, 5 ]
list2 = ["a", "b", "c", "d"]
list3= [] ##空列表
更新列表:
list = []
list.append('Hello') ## 使用 append() 添加元素
list.append('World')
print list
##输出:
['Hello', 'World']
删除元素:
list = ['a', 'b', 1111, 2222]
del list[2]
print list
##结果:
## ['a', 'b', 2222]
Set(集合):
一个无序的不重复元素序列。
空集用set(),不能用{},{}是用来创建空字典的。
创建集合:
set1 = {'hello','world','hello'} #方式1
set2 = set('abcdefg') #方式2
print(set1)
print(set2)
##结果:
##{'helllo','world'} ##有去重功能
##{'a','b','c','d','e','f','g'}
Dictionary(字典):
{}空字典
关键值+对应数据
dict = {'a': 'Acc', 'b': 666, 'c': 'ccc'}
print "dict['a']: ", dict['a']
print "dict['b']: ", dict['b']
dict['b'] = 999 ## 更新
dict['d'] = "ddd" ## 添加
print "dict['b']: ", dict['b']
print "dict['d']: ", dict['d']
##结果:
##dict['a']: Acc
##dict['b']: 666
##dict['b']: 999
##dict['d']: ddd
——————————————————————————————————————————
for in [ ]
for a in [1]:
print(a)
##输出: 1
for a in [1,2,3]:
print(a)
##输出:
##1
##2
##3
——————————————————————————————————————————
os.path.join的用法
import os
p1 = 'first'
p2 = 'second'
name = 'ccc.txt'
p3 = os.path.join(p1,"ABCDE",p2+name)
print ( p3 )
##结果:
##first/ABCDE/secondccc.txt
——————————————————————————————————————————
python面向对象
类的私有属性
__xxxx:类的属性名中,两个下划线开头,则该属性为私有,不能在类的外部被使用或直接访问。
类的继承
class student(people): ##类student继承类people
class sample(speaker,student): ##多重继承
__init__ : 构造函数,在生成对象时调用
——————————————————————————————————————————
[]用法
a='python'
d=a[:-1] #从位置0到位置-1之前的数
print(d) #pytho
e=a[:-2] #从位置0到位置-2之前的数
print(e) #pyth