python学习笔记(四)

1) 类。 python类的方法需要传self作为参数。(self是习惯性的约定,并不是强制的)。python的构造函数名叫作__init__(),而在实例化python的时候,并不需要使用new关键字(@_@太奇怪了,这什么语法啊?)另外,和__init__()相对的,还有__del__()方法,和destructor相对应。
=================================
class Person:
~def __init__(self, name):
~~self.name = name

~def sayHi(self):
~~print 'Hello, my name is', self.name

p = Person('Swaroop')
p.sayHi()

=================================

2) 类变量。 python的类变量是定义在和方法同一级的,在调用的时候要使用类名.变量名的方式。类变量是所有对象(实例)共享的,对象变量是单独的,互不影响的。
=================================
class Person:
~'''Represents a person.'''
~population = 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
=================================

3) python的继承看起来真是丑陋啊!
=================================
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
=================================

4) 读写文件。 python读写文件有“w”,“r”,“a”三种模式,分别代表“写”,“读”和“追加”。和ruby一样,打开文件还要关闭文件。
=================================
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''


f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()

    if len(line) == 0: # Zero length indicates EOF
        break
    print line,
    # Notice comma to avoid automatic newline added by Python
f.close() # close the file
=================================

5) 导入模块的时候,可以通过as关键字,将模块重命名。

6) 存储器。 python中有存储器的概念,它有点奇怪,有点像对象的序列化和反序列化,但它是将对象保存到一个文件中,而不是将对象和字符串之间进行转换。存储器的相关模块为cPickle(Pickle),存储的方法为dump(),读取的方法为load()。
=================================
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')
p.dump(shoplist, f)
# dump the object to a file
f.close()

del shoplist # remove the shoplist

# Read back from the storage

f = file(shoplistfile)
storedlist = p.load(f)

print storedlist
=================================

7)
try..except。 python中捕获异常的语句怎么也这么奇怪呢?算不,反正比ruby人捕获异常语句好太多了。
=================================
import sys

try:
    s = raw_input('Enter something --> ')
except EOFError:
    print '\nWhy did you do an EOF on me?'
    sys.exit() # exit the program
except:
    print '\nSome error/exception occurred.'
    # here, we are not exiting the program

print 'Done'
=================================

8) try .. finally。 和别的语言一样。
=================================
import time

try:
f =
file('poem.txt')
    while True: # our usual file-reading idiom
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2)
        print line,
finally:
f.close()

    print 'Cleaning up...closed the file'
=================================

9) 时间间隔。 python中的定时器是通过time模块的sleep()方法实现的。sleep()方法接收一个参数,单位为秒(不是微秒)。

10) 
常用的内建函数。
函数名                      功能
dir(obj)                    显示对象的属性,如果没有提供参数,则显示全局变量的名字
help(obj)                   显示对象的字符串文档,如果没有提供参数,则会进入交互式帮助
int(obj)                    将一个对象转换为整型
len(obj)                    返回对象的长度
open(fn, mode)              以mode方式打开文件fn
range([start,]stop[,step]) 返回一个整型列表,起始值为start,结束值为stop-1,start默认为0,step默认为1
raw_input(str)              等待用户输入一个字符串,str作为提示信息
str(obj)                    讲一个对象转换为字符串
type(obj)                   返回对象的类型
posted on 2010-07-12 00:30  真阿当  阅读(102)  评论(0编辑  收藏  举报