Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92779
  • 博文数量: 23
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 253
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-01 20:41
文章分类

全部博文(23)

分类: Python/Ruby

2015-03-09 17:41:02

python:跨平台、面向对象的动态编程语言

发布时间:1991年

发明:guido van rossum

 

 

python的语言特点

1、开源免费

2、脚本语言,解析执行

3、跨平台

4、简洁美观

5、一切皆对象

6、可扩展的胶水语言

 

解析执行原理:

1、编辑文本文件

2、意识编译字节码,形成pyc源码

3、在pvm虚拟机执行

4、在cpu执行,打印到屏幕

解析器cpython、jpython、ironpython

 

 

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

1、python环境准备

执行命令:python --version 打印出版本号

2、python安装

1、预安装:linux、unix、macos一般都是自带安装python

2、源码安装

3、安装包安装 rpm、msi(windows)

a)、源码编译安装

wget

tar xjvf python-3.3.2.tar.bz2

cd python-3.3.2

./configure

make

make install

ln -s /usr/loacl/bin/python3 /usr/bin/python

 

 

3、基本语法

1、>>> print('hello')

>>> 是主提示符

2、 ... print 'hello'  

...是辅助提示符

3、>>> exit()

退出

 

 

 

 

root@localhost# python

 

>>>print ('hello')

hello

 

>>>if 1 + 1 == 2: 冒号不是分号

...                print 'hello'

...

hello

>>>exit()   就退出来了。

 

 

4、python的自省

 

>>> help(str)  遇到问题可以help

>>>type('hello')

>>>isinstance('hello',str)

>>>dir(str)

 

 

 

5、模块导入

1、import m

   print m.plus(1,2)

2、from m import plus

print plus(1,2)

示例:                                               m.py ,                 new.py

  def plus(a,b):              import m

      return a + b            print m.plus(1,2)

  def plus2():              

  exit()                  打印结果 3

 

6、导入系统模块

1、import sys.path

   from os import *

  

7、导入私有模块

1、           import sys

2、        path = '/root/dir/' 把模块的目录添加到path中,方便查找加载

3、        sys.path.append(path)   或者直接  sys.path.append("root/dir/")

4、        from m import plus2

 

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

 

8、变量的使用

内建数据类型:

1、boolean  --> exam_is_pass = true

2、integer  --> person_number = 100

3、float    --> weight = 65.18

4、string   --> greet_msg = "welcome to visit itercast"

5、list     --> score_list = [12, 25, 56, 78]   顺序存储相当于数组,字符串和数字混合

6、tuple        --> index_tuple(0, 1, 2, 3, 4)      不能改变的数组

7、dict                -->age_dict = { 'bob': 18, 'lucy': 16} 字典

8、set      --> index_set = set([0, 1, 2, 3])      集合,和数学里面的集合一样没有顺序

9、none 空字符串‘ ’ 、空元组()、空列表[]、空字典{} ,在逻辑判断的时候都是false

>>> 'i love "itercast"'

           'i love "itercast"'

>>> "i love \"itercast\""

'i love "itercast"'

>>> str1 = '''i love

... "itercast"

... '''

>>> str1

'i love \n"itercast"\n'

 

 

字符串和list之间的转换:

>>> list1 = str1.split()

>>> list1

>>> ['i', 'love', '"itercast"']

 

往list里面添加字符串

list1.append('!') or ("!")

 

往list里面添加数字

list1.append(8)

 

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

9、 字典使用:

字典名 = {’关键字‘:值,...}

字典名.get('关键字',默认值)

赋值:自顶名['关键字'] = 值

字典名.keys()           将关键字返回出一个列表

字典名.values()         将字典的值返回出一个列表

字典名.copy()          age_dict2 = age_dict.copy()

>>> del age_dict['bob']

>>> age_dict2.popitem()      弹出第一项

>>> bob in age_dict2

在脚本里面写:

dirt = {'bob':10, 'lucy':20, 'jim':30}      定义字典

print dirt['bob']

dirt['abc']=40     添加元素

print dirt

del  dirt['bob']

字典内置函数&方法

Python字典包含了以下内置函数:

1、cmp(dict1, dict2):比较两个字典元素。

2、len(dict):计算字典元素个数,即键的总数。

3、str(dict):输出字典可打印的字符串表示。

4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。

Python字典包含了以下内置方法:

1、radiansdict.clear():删除字典内所有元素

2、radiansdict.copy():返回一个字典的浅复制

3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值

4、radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值

5、radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false

6、radiansdict.items():以列表返回可遍历的(键, 值) 元组数组

7、radiansdict.keys():以列表返回一个字典所有的键

8、radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default

9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里

10、radiansdict.values():以列表返回字典中的所有值

 

 

false

 

实例:

>>>dirt = { 'bob':10, 'lucy':20, 10:10}

>>> dirt['jim'] = 30

返回关键字的列表

>>> dirt.keys()

['jim', 'bob', 10, 'lucy']

返回值得列表

>>> dirt.values()

[30, 10, 10, 20]

list复制:

>>> dir1 = dirt.copy()

>>> dir1.values()

[10, 30, 10, 20]

>>> dir1.keys()

['bob', 'jim', 10, 'lucy']

list删除关键字

del dirt['bob']

list弹出第一个关键字

dirt.popitem()

 

Python 表达式:

 

=                     赋值

==                   等于

>,<                         大于号和小于号

>=,<=                     大于等于和小于等于

And                        逻辑与

Or                           逻辑或

Not                         逻辑非

if 1==1 and 2==2:

        print 'hello'

else:

        print 'error'

 

 

 

 

python的逻辑分支:

If  条件判断语句                if条件判断语句

. . . .                                   

else                                        elif 条件判断语句

. . . .                                    

. . . .                               else

 .                                                 

 

Python 没有switch语句

if  sys.argv[1] == '-s':

time.sleep(10);

elif sys.argv[1] == '-q':

quit();

else:

print('error')

 

例子:

sex = 'boy'

age = 19

if sex == 'boy':

        print 'hi,boy'

elif sex == 'girl':

        if age < 18:

                print 'hi,girl'

        else:

                print 'hi,lady'

else:

        print 'weather is good'

print 'end'

 

 

python循环:

for循环:

例一:

IndentationError: unexpected indent

>>> for i in ['bob', 'lucy', 'jim']:

...     print i,

...

bob lucy jim

>>> for i in ['bob', 'lucy', 'jim']:

...     print i

...

bob

lucy

jim

 

例二:

for name,age in (('afe',18), ('fleajf',16)):

>>> for name,age in (('afe',18), ('fleajf',16)):

...     print name,age

...

afe 18

fleajf 16

 

While 循环:

>>> i = 0

>>> while i < 10:

...     print i,

...     i += 1

 

迭代器:

>>> obj = range(5)

>>> itera = iter(obj)   相当于 obj._iter_()

>>> try:

...     while True:

...             print itera.next(),

... except StopIteration:

...     pass

...

0 1 2 3 4

 

 

 

python 函数定义:

1、不带参数函数的定义

函数定义

函数调用

def 函数名()

函数体

函数名()

实例: def welcome():

print( ' I love it')

 

2、带参数函数的定义

函数定义

函数调用

def 函数名(参数列表):

函数体 。。。

函数名(参数列表)

例子:

>>> def welcome(who,action):

...     print(who + ' ' + action)

...

>>> welcome('wang','nihao')

wang nihao

 

3Python变成参数:参数会自动转变成一参数命名的元组或字典

函数定义1

函数定义2

def 函数名(*args):转换成元组

函数体 。。

函数名(v1v2v3

def 函数名(**args):转换成字典

函数名

函数名(k1=v1k2=v2

 

1

2

1

>>> def welcome(*args):

...     print args

...

>>> welcome('jim','is','thinking')

('jim', 'is', 'thinking')

>>> def welcome(**args):

...     print args

...

>>> welcome(who='jim',state='is',action='thinking')

{'action': 'thinking', 'state': 'is', 'who': 'jim'}

 

 

 

4、参数默认值

>>> def welcome(who,state='is',action='sleeping'):

...     print who,state,action

...

>>> welcome('jim','was')

jim was sleeping

 

第一个参数必须有,第二个和第三个可以没有,没有就用默认值

 

5、函数的返回值

def 函数名(函数列表)

def 函数名(参数列表)

def 函数名(参数列表)

函数体

函数体 

函数体

return obj

return

 

返回 obj对象

返回none

返回none

 

 

 

 

 

面向对象基础--

Python种一切都是对象,雷和对象是面向对象的基础

 

定义类

类的实例化

class 类名称():默认继承object

· · · · ·

class 类名称(father):

· · · · ·

 

实例名=类名称()

 

例子:

定义一个类

实例化monk

查看实例化类的类型

class monk:

        def __init__(self,name,age):

                self.name = name

                self.age = age

 

yc_monk = mokn('yancan',  20)

yc_monk.name #成员变量

 

yc_monk._class_

type(yc_monk)

类的方法:

 

类的方法

实例化方法的调用

class 类名称

def 方法名(self,参数列表)

。。。

 

实例名.方法名(参数列表)

 

例子

class monk:

def __init__(self, name, age):

self.name = name

self.age = age

def net(self):

print "i love webo"

def play(self, str):

print "play with",str

m1 = monk("yancan", 19)

print m1.name

m1.net()

m1.play("monkey")

 

 

python文件IO

print方法:输出数据到标准输出

raw_ipnut方法:从标准输入读数据

从标准输入读取内容

将用户输入的信息输出到标准输出

>>> input = raw_input('prompt@ ')

prompt@  nihaowoshi

>>> print(input)

nihaowoshi

 

 

file-读文件

 

创建一个file类实例f,以只读模式打开文本文件

>>>  f = file('1.txt', 'r')

通过f实例读取文件内容

>>> f.read()

关闭文件实例,释放资源

>>> f.close()

使用open函数打开文件,返回一个file类实例

>>> f  = open('1.txt', 'r')

读取全部,返回字符串

>>> f.read()

一次只读取一行

>>> f.readline()

读取全部返回列表

>>> f.readlines()

已追加模式打开文件,返回一个file类实例

>>> f = file('1.txt','a')

向文件写入字符串

>>> f.write('I love you\nEnd')

刷新缓冲区

>>> f.flush()  

>>> f.close()

"r"   ------->     只读

 

"w"  ------->     只写

 

"a"   ------->     追加

 

"b"   ------->     二进制

 

"r+","a+"  -------> 更新

 

阅读(1451) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~