python 学习
1.python解释器
cPython JPython IPython PyPy Jython IronPython
2.第一个python程序
python
print 'hello world'
print 'hello','pyhton','world' /*逗号分隔,显示为空号分隔*/
print 100
print 100+300
shell 方式
vim hello.py
#!/usr/bin/env python /**如果不加这行,那么需要python环境*/
print 'hello','pyhton','world'
运行方式
python hello.py
./hello.py
3.基本语法
3.1 输入输出
>>> name = raw_input()
ssss
>>> print name
ssss
>>>
name = raw_input('please enter your name: ')
print 'hello,', name
数据类型
面向对象高级特性
>>> def set_age(self, age): # 定义一个函数作为实例方法
... self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s, Student) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25
但是,给一个实例绑定的方法,对另一个实例是不起作用的:
>>> s2 = Student() # 创建新的实例
>>> s2.set_age(25) # 尝试调用方法
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
为了给所有实例都绑定方法,可以给class绑定方法:
>>> def set_score(self, score):
... self.score = score
...
>>> Student.set_score = MethodType(set_score, None, Student)
给class绑定方法后,所有实例均可调用:
>>> s.set_score(100)
>>> s.score
100
>>> s2.set_score(99)
>>> s2.score
99
使用slots
但是,如果我们想要限制class的属性怎么办?比如,只允许对Student实例添加name和age属性。
为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的slots变量,来限制该class能添加的属性:>>> class Student(object):
… slots = (‘name’, ‘age’) # 用tuple定义允许绑定的属性名称
s = Student() # 创建新的实例
>>> s.name = 'Michael' # 绑定属性'name'
>>> s.age = 25 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
File "&