<span style="font-size:14px;"># -*- coding: cp936 -*-
#类的定义
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
#3.0之后的用法 nolocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print "after local assignment:",spam
do_nonlocal()
print "after nonlocal assignment:",spam
do_global()
print "after global assignment:",spam
scope_test()
print "in global scope:",spam
print ("-")*40
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
#类属性
print MyClass.i
#结果:12345
#文档注释
print MyClass.__doc__
#结果:A simple example class
x = MyClass()
#报错
#print MyClass.f()
#方法有一个特性就是实例对象被当做第一个参数传递给了函数
print x.f()
#结果:hello world
#数据属性不需要申明。像局部变量一样,当他们初次赋值的时候他们就存在了。
x.counter = 1
while x.counter < 10:
x.counter = x.counter*2
print(x.counter)
del x.counter
print ("-")*40
'''
实例化操作(调用类对象)将会创建一个空对象。
许多类可以用设置特定的初始状态来创建对象。因此类可以定义一个名叫_init()的特殊方法。
当类定义_init()方式时,类实例化就会自动调用_init_()方法为新创建的类实例。
'''
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(2.0,-5.34)
print x.r,x.i
#结果:2.0 -5.34
# Function defined outside the class
def f1(self, x, y):
return min(x, x+y)
class C:
f = f1
def g(self):
return 'hello world'
h = g
c1 = C()
print c1.f(1,2)
#方法可以通过用方法属性self 可以调用其他方法。
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
#继承
'''
class DerivedClassName(BaseClassName):
<statement-1>
<statement-N>
名称BaseClassName 必须定义在一个包含派生类定义的作用域中。在基类名称的位置上,其他随意表
达式都是允许的、例如,当基类定义在其他模块中,这也是可用的。
class DerivedClassName(modname.BaseClassName):
在派生类中一个重写方法
事实上想扩展方法,而不是简单的代替同名的基类方法。最简单直接调用基
类的方法就是用: BaseClassName.methodname(self, arguments)
Python 有两种实现继承的内置函数:
方法一: 用isinstance()方法来检查实例类型:只有obj._class_is 是整型或者其他从int 继承的类,
isinstance(obj, int)才会返回真。
方法二: 用issubclass()方法来检查类继承:issubclass(bool, int)结果是真得,因为bool 是int 的一个子
类。但是issubclass(float, int)是假的因为float 不是int 的子类。
'''
class BagSub(Bag):
print "this is subclass!"
bagsub1 = BagSub()
bagsub1.add(10)
print bagsub1.data
#结果:this is subclass! [10]
#多继承
'''
class DerivedClassName(Base1, Base2, Base3):
在同一等级重复的同样类中执行两次。因此,如果一个属性没在派生类中找到,首先会在base1
然后再base1 的基类中,如果在那里都没发现,就会在base2 中查找等等。
'''
#私有变量
'''
除了对象内部其他都不能访问的“私有”变量在python 中是不存在的。但是,大多数python 代码都
遵守一个规则:以下划线为前缀的名称被看成是API 的非公共部分。它可以认为是一个细节实现并且改变
时不需通知。至少是两个开头下划线。
'''
#名字变换对于让子类在不影响父类方法前提下重载方法很有重要意义
class Mapping:
def __init__(self,iterable):
self.items_list = []
self.__update(iterable)
def update(self,iterable):
for item in iterable:
self.items_list.append(item)
__update = update #重命名
class MappingSubclass(Mapping):
def update(self,keys,values):
#提供了新的实现 不影响__init__()
for item in zip(keys,values):
self.items_list.append(item)
#备注
class Employee:
pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
print john.name,john.dept,john.salary
#结果:John Doe computer lab 1000
#异常
class ExceptionB(Exception):
pass
class ExceptionC(ExceptionB):
pass
class ExceptionD(ExceptionC):
pass
for c in [ExceptionB,ExceptionC,ExceptionD]:
try:
raise c()
except ExceptionD:
print "d"
except ExceptionC:
print "c"
except ExceptionB:
print "b"
#结果:dcb
#注意如果异常语句进行翻转(except ExceptionB在前),它将会打印出BBB,-
#迭代器
class Reverse:
def __init__(self,data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
rev = Reverse('hello')
iter(rev)
for char in rev:
print (char)
#可以打出
#生成器:
'''
生成器是一个创建迭代器的简单而有力的工具。它们书面写时就像规范的函数,但是用yield 语句在
任何时候都可以返回数据。每次在它上调用next()方法,生成器继续回到一起它离开的位置。(它记录所
有数据值以及最后执行的语句)。
'''
def reverse(data):
for index in range(len(data)-1,-1,-1):
yield data[index]
for char in reverse("hello"):
print char,
#:o l l e h
</span>