1.python 面向对象编程
给C/C++/Java/C#程序员的注释
注意,即便是整数也被作为对象(属于int
类)。这和C++、Java(1.5版之前)把整数纯粹作为类型是不同的。通过help(int)
了解更多这个类的详情。 C#和Java 1.5程序员会熟悉这个概念,因为它类似与 封装与解封装 的概念。
创建类
使用class
关键字创建。类的域和方法被列在一个缩进块中。
#!/usr/bin/python
# Filename: simplestclass.py
class Person:
pass # An empty block
p = Person()
print p
给C++/Java/C#程序员的注释
Python中的self
等价于C++中的self
指针和Java
当你调用这个对象的方法MyObject.method(arg1, arg2)
的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)
——这就是self
的原理了。、C#中的this
参考。
2、构造函数
给C++/Java/C#程序员的注释
__init__
方法类似于C++、C#和Java中的 constructor 。
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()
# This short example can also be written as Person('Swaroop').sayHi()
3.析构函数
给C++/Java/C#程序员的注释
Python中所有的类成员(包括数据成员)都是 公共的 ,所有的方法都是 有效的 。
只有一个例外:如果你使用的数据成员名称以 双下划线前缀 比如__privatevar
,Python的名称管理体系会有效地把它作为私有变量。
这样就有一个惯例,如果某个变量只想在类或对象中使用,就应该以单下划线前缀。而其他的名称都将作为公共的,可以被其他类/对象使用。记住这只是一个惯例,并不是Python所要求的(与双下划线前缀不同)。
同样,注意__del__
方法与 destructor 的概念类似。
4.类对象和实例对象
#!/usr/bin/python
# Filename: objvar.py
class Person:
'''Represents a person.'''
<span style="color:#ff0000;">population</span> = 0
def __init__(self, name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
'''I am dying.'''
print '%s says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % Person.population
def sayHi(self):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
5.继承
#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print '(Initialized SchoolMember: %s)' % self.name
def tell(self):
'''Tell my details.'''
print 'Name:"%s" Age:"%s"' % (self.name, self.age),
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print '(Initialized Teacher: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Salary: "%d"' % self.salary
class Student(SchoolMember):
'''Represents a student.'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print '(Initialized Student: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Marks: "%d"' % self.marks
t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
Python不会自动调用基本类的constructor,你得亲自专门调用它。
6.输入/输出 --- 文件处理和使用储存器模块。
使用文件:
<strong>#!/usr/bin/python
# Filename: using_file.py
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
<span style="color:#ff0000;">f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file</span>
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
<span style="color:#ff0000;">line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break</span>
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file</strong>
7.存储器 cPickle(对象持久化)
cPickle
,它的功能和
pickle
模块完全相同,只不过它是用C语言编写的,因此要快得多(比
pickle
快1000倍)。
#!/usr/bin/python
# Filename: pickling.py
import cPickle as p
#import pickle as p
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
<span style="color:#ff0000;">p.dump(shoplist, f)</span><span style="color:#663300;"> # dump the object to a file</span>
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = <span style="color:#ff0000;">p.load(f)</span>
print storedlist
8. 异常
处理异常
<strong>#!/usr/bin/python
# Filename: try_except.py
import sys
<span style="color:#ff0000;">try:</span>
s = raw_input('Enter something --> ')
<span style="color:#ff0000;">except EOFError:#捕获特定异常</span>
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
<span style="color:#ff0000;">except:#捕获所有异常</span>
print '\nSome error/exception occurred.'
# here, we are not exiting the program
#捕获只进行一次
print 'Done'</strong>
你还可以让try..catch
块关联上一个else
从句。当没有异常发生的时候,else
从句将被执行。主动抛异常
<span style="font-family:Simsun;font-size:14px;"><strong><span style="color:#663300;">#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
</span><span style="color:#ff0000;"> raise ShortInputException(len(s), 3)</span><span style="color:#663300;">
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length, x.atleast)
else:#</span><span style="color:#990000;">若无异常则执行else</span><span style="color:#663300;">
print 'No exception was raised.'</span></strong></span>
try-except-finally这种语法是在py2.5中才支持的
9.python 标准库
import sys
对于有经验的程序员,sys
模块中其他令人感兴趣的项目有sys.stdin
、sys.stdout
和sys.stderr
它们分别对应你的程序的标准输入、标准输出和标准错误流。
import os
这个模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。
-
os.name
字符串指示你正在使用的平台。比如对于Windows,它是'nt'
,而对于Linux/Unix用户,它是'posix'
。 -
os.getcwd()
函数得到当前工作目录,即当前Python脚本工作的目录路径。 -
os.getenv()
和os.putenv()
函数分别用来读取和设置环境变量。 -
os.listdir()
返回指定目录下的所有文件和目录名。 -
os.remove()
函数用来删除一个文件。 -
os.system()
函数用来运行shell命令。 -
os.linesep
字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n'
,Linux使用'\n'
而Mac使用'\r'
。 -
os.path.split()
函数返回一个路径的目录名和文件名。
特殊方法:
名称 | 说明 |
---|---|
__init__(self,...) | 这个方法在新建对象恰好要被返回使用之前被调用。 |
__del__(self) | 恰好在对象要被删除之前调用。 |
__str__(self) | 在我们对对象使用print 语句或是使用str() 的时候调用。 |
__lt__(self,other) | 当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。 |
__getitem__(self,key) | 使用x[key] 索引操作符的时候调用。 |
__len__(self) | 对序列对象使用内建的len() 函数的时候调用。 |
列表综合
<span style="color:#330000;">#!/usr/bin/python
# Filename: list_comprehension.py
listone = [2, 3, 4]
</span><span style="color:#ff0000;">listtwo = [2*i for i in listone if i > 2]</span><span style="color:#330000;">
print listtwo</span>
在函数中接收元组和列表
<span style="color:#663300;">>>> def powersum(power, </span><span style="color:#ff0000;">*args</span><span style="color:#663300;">):
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... </span><span style="color:#ff0000;">for i in args:</span><span style="color:#663300;">
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100</span>
由于在
args
变量前有
*
前缀,所有多余的函数参数都会作为一个元组存储在
args
中。如果使用的是
**
前缀,多余的参数则会被认为是一个字典的键/值对。
6
</pre><pre name="code" class="python">#!/bin/env python
#-*- encoding: utf-8 -*-
import httplib
import time
import urllib
def query():
try:
body = '{"user_name":"张三11","id_card":"330829199101219999","group_id":1}'
headers = {"accesstoken":"0951a80bd43a56e14582c49869848b3ab95379b9"}
conn = httplib.HTTPConnection("baiduurl", "80", False, 60)
url = '/goods/1'
conn.request('GET', url = url, headers = headers,body = body)
#conn.request('POST',url = url, body = body, headers=headers)
response = conn.getresponse()
res=response.status
print(response.getheaders())
print(response.read())
if res == 200:
return ""
else:
return res
except Exception, e:
conn.close()
return -1
print query()