python学习

本文介绍了Python编程的基本概念,包括Python解释器、编写第一个Python程序和核心语法。重点讲解了输入输出、数据类型和面向对象高级特性,如slots、@property装饰器的使用。此外,还讨论了Python中的多重继承和Mixin类的设计,以及文件的读写操作,包括读取二进制文件、字符编码和自动编码转换。
摘要由CSDN通过智能技术生成

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 "&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值