一、list, tuple, set 和 dict的使用
多使用list, tuple, set 和 dict这几种数据类型,它们分别用[]、()、([])和{}定义。
tuple_name=(“apple”,”banana”,”grape”,”orange”)
list=[“apple”,”banana”,”grage”,”orange”]
dict={“a”:”apple”, “b”:”banana”, “g”:”grage”, “o”:”orange”}
字符串:注意区别str和unicode
在Python中定义一个Unicode字符串,需要在引号前面加上一个字符u,
当使用utf-8编码时,非unicode字符中一个汉字的长度是3,而使用gb2312时是2
unicode = u'我'
str = '我'
print len(unicode),len(str)
unicode = u'我'
str = '我'
print len(unicode),len(str)
str1 = u'我是派森'
print str1[2:4]
列表list:
array = [1,2,3]
print array[0]
array[0] = 'a'
print array
元组tuple:
test = [0]
print type(test)
test = [0,]
print type(test)
test = (0,)
print type(test)
test = (0)
print type(test)
test = 0,
print type(test)
二、python中的运算符、表达式和流程控制:
(1) Python的算术运算符除了+、-、*、/、%(取余数)之外,还有求幂(**)和取模
(2) Python支持复合赋值(x+=1),但不支持C
(3) Python用and、or、not代替了C
(4) Python的选择语句包括if、elif和else,记得后边加冒号;Python中没有switch,但可以用if-elif-else或dict完成相同的任务模拟;
def print_one():
print 'one'
def print_two():
print 'two'
numtrans = {
1:print_one,
2:print_two,
}
try:
numtrans[x]()
except KeyError:
print 'nothing!'
(5) Python的循环语句有while、for,它们都支持else语句;注意Python的for相当于C
(6) 两种语言的异常处理语句基本一致,不同的是Python的异常处理也支持else。
try:
f = open('thefile.txt')
s = f.readline()
...
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
finally:
f.close()
三、面向对象编程的基本知识
(1) Python用class关键字、类名、括号加父类(可选)及冒号定义类,实例化类时不需要new关键字;
(2) Python可以对象中动态添加成员变量,但建议在__init__函数中添加成员变量并初始化;
(3) Python的类中可以通过名称前加双下划线定义私有变量(及私有方法);
(4) Python中定义类的方法与定义普通函数在语法上基本相同,区别是非静态方法的第一个参数总是类的实例,即self;
(5) 通过修饰符@staticmethod可以定义一个类的静态方法;
(6) Python对类方法重载和运算符重载,通过内置的运算符方法来实现
class A:
def __init__(self,sum = 0):
self.sum = sum
def __add__(self,x):
return A(self.sum + x.sum)
def __str__(self):
return str(self.sum)
a = A(1)
b = A(2)
print a + b
(7) Python支持类的单继承和多继承,但不支持接口,也不(直接)支持抽象类;
(8) 通过自省,可以在运行时获得对象的有用信息。
常用的自省函数包括:
* id() 返回对象唯一的标识符
* repr() 返回对象的标准字符串表达式
* type() 返回对象的类型
* dir() 返回对象的属性名称列表
* vars() 返回一个字典,它包含了对象存储于其__dict__中的属性(键)及值
* hasattr() 判断一个对象是否有一个特定的属性
* getattr() 取得对象的属性
* setattr() 赋值给对象的属性
* delattr() 从一个对象中删除属性
* callable() 测试对象的可调用性
* issubclass() 判断一个类是另一个类的子类或子孙类
* isinstance() 判断一个对象是否是另一个给定类的实例
* super() 返回相应的父类