In [1]:
class Person:
    """
    person defined
    """
    def setname(self, name):
        """
        set person name
        """
        self.name = name

    def show(self):
        """
        show person name
        """
        print self.name

类对象


In [11]:
# 执行时产生类对象,并赋值给class后的变量
class A:
    """
    class A here
    """
    pass

A


Out[11]:
<class __main__.A at 0x104587808>

In [3]:
# 类内的赋值语句会创建类的属性
# 类属性提供对象的状态和行为
class B:
    x = 10
    
    def getname(self):
        print id(self), type(self)
    
print B.x
print B.getname


10
<unbound method B.getname>

实例对象


In [5]:
a = A()
print a


<__main__.A instance at 0x104593290>

In [6]:
b = B()
print id(b)
b.getname()


4367925048
4367925048 <type 'instance'>

In [14]:
dir(a)
print A.__doc__


    class A here
    

构造函数


In [19]:
class Person:
    """
    person defined
    """
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print 'constructor is called:',self.name
    
    def setname(self, name):
        """
        set person name
        """
        self.name = name

    def show(self):
        """
        show person name
        """
        print self.name

In [20]:
p1 = Person("joe", 20)


constructor is called: joe

In [21]:
p2 = Person("kate", 19)


constructor is called: kate

析构函数


In [22]:
class Person:
    """
    person defined
    """
    def __del__(self):
        print 'destructor is called'

    # 默认参数
    def __init__(self, name="a", age=20):
        self.name = name
        self.age = age
        print 'constructor is called'

    def setname(self, name):
        """
        set person name
        """
        self.name = name

    def show(self):
        """
        show person name
        """
        print self.name

In [23]:
p = Person()


constructor is called

In [24]:
del p


destructor is called

In [25]:
# 作用域
def call_one():
    q = Person()
    return None

call_one()


constructor is called
destructor is called

运算符重载


In [31]:
class Person:
    """
    person defined
    """
    def __str__(self):
        return 'Person name:%s and age:%d' % (self.name, self.age)
    
    #def __repr__(self):
    #    return '[REPR]Person name:%s and age:%d' % (self.name, self.age)

    def __del__(self):
        print 'destructor is called'

    def __init__(self, name="a", age=20):
        self.name = name
        self.age = age
        print 'constructor is called'

    def setname(self, name):
        """
        set person name
        """
        self.name = name

    def show(self):
        """
        show person name
        """
        print self.name

In [32]:
p = Person()
print p


constructor is called
Person name:a and age:20

In [33]:
p


Out[33]:
<__main__.Person instance at 0x10470e9e0>

In [36]:
p1 = eval(repr(p))


  File "<string>", line 1
    <__main__.Person instance at 0x10470e9e0>
    ^
SyntaxError: invalid syntax

索引迭代


In [37]:
class stepper:
    def __getitem__(self,i):
      return self.data[i]

X = stepper()
X.data="Spam"

print X[1]


p

属性引用


In [39]:
class empty:
  def __getattr__(self,attrname):
    if attrname == "age":
      return 40
    else:
      raise AttributeError,attrname


X = empty()
X.age        #Print 40

X.name       #AttributeError:name


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-39-720f79b9ea69> in <module>()
     10 X.age        #Print 40
     11 
---> 12 X.name       #AttributeError:name

<ipython-input-39-720f79b9ea69> in __getattr__(self, attrname)
      4       return 40
      5     else:
----> 6       raise AttributeError,attrname
      7 
      8 

AttributeError: name

类的继承


In [40]:
class Chinese(Person):
    pass

In [41]:
c = Chinese()
print c.name


constructor is called
a

In [42]:
c.show()
print c


a
Person name:a and age:20

In [43]:
# 稍微复杂
class CAnimal:
    def __init__(self,voice='hello'): # voice初始化默认为hello
        self.voice = voice
    def Say(self):
        print self.voice
    def Run(self):
        pass    # 空操作语句(不做任何操作)

class CDog(CAnimal):          # 继承类CAnimal
    def SetVoice(self,voice): # 子类增加函数SetVoice
        self.voice = voice
    def Run(self):            # 子类重载函数Run
        print 'Running'

dog = CDog()
dog.SetVoice('I am a dog!') 
dog.Say()
dog.Run()


I am a dog!
Running

多重继承


In [44]:
class C2: pass
class C3: pass
class C1(C2, C3): pass

静态方法和类方法


In [45]:
class TestClass():

    def callFunc(self):
        print 'callFunc'

    @staticmethod
    def callStatic():
        print 'static call'

    @classmethod
    def callClass(cls):
        print 'class call'

In [46]:
c = TestClass()
c.callFunc()
c.callStatic()
c.callClass()


destructor is called
callFunc
static call
class call

In [48]:
#TestClass.callFunc()
TestClass.callStatic()
TestClass.callClass()


static call
class call

新式类的区别


In [49]:
class E:    
#经典类  
    pass  
      
class E1(object):    
#新式类  
    pass  
       
e = E()  
print "经典类"  
print e  
print type(e)  
print e.__class__  
  
print "新式类"  
e1 = E1()  
print e1  
print type(e1)
print e1.__class__


经典类
<__main__.E instance at 0x10473e248>
<type 'instance'>
__main__.E
新式类
<__main__.E1 object at 0x1047098d0>
<class '__main__.E1'>
<class '__main__.E1'>

In [50]:
class A(object):    
    """ 
    新式类 
    作为所有类的基类 
    """  
    def foo(self):    
        print "class A"   
          
class A1():    
    """ 
    经典类 
    作为所有类的基类 
    """  
    def foo(self):    
        print "class A1"    
          
class C(A):    
    pass  
      
class C1(A1):    
    pass  
      
class D(A):    
    def foo(self):    
        print "class D"    
      
class D1(A1):    
    def foo(self):    
        print "class D1"    
          
    
    
class E(C, D):    
    pass  
      
class E1(C1, D1):    
    pass  
  
e = E()  
e.foo()  
    
  
e1 = E1()  
e1.foo()


class D
class A1

In [51]:
class A(object):    
    __slots__ = ('name', 'age')   
  
class A1():    
    __slots__ = ('name', 'age')   
      
a1 = A1()  
a = A()  
  
a1.name1 = "a1"  
a.name1 = "a"


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-51-4bccab65f985> in <module>()
      9 
     10 a1.name1 = "a1"
---> 11 a.name1 = "a"

AttributeError: 'A' object has no attribute 'name1'

In [52]:
class A(object):    
    def __getattribute__(self, *args, **kwargs):    
        print "A.__getattribute__"  
          
      
class A1():    
    def __getattribute__(self, *args, **kwargs):    
        print "A1.__getattribute__"  
          
      
a1 = A1()  
a = A()  
  
a.test  
print "========="  
a1.test


A.__getattribute__
=========
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-52-2d300a523323> in <module>()
     14 a.test
     15 print "========="
---> 16 a1.test

AttributeError: A1 instance has no attribute 'test'

类的私有属性


In [55]:
class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.publicCount
# print counter.__secretCount  # 报错,实例不能访问私有变量
print counter._JustCounter__secretCount # 这样就可以访问了,伪私有变量


1
2
2
2

In [58]:
class A(object):
    def __func(self):pass
    
print A.__dict__
a = A()
a._A__func()


{'__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__module__': '__main__', '_A__func': <function __func at 0x10473d398>, '__doc__': None}

异常处理器

默认异常处理器


In [1]:
x, y = 5, 0
x/y


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-3ef7a5b5d2dd> in <module>()
      1 x, y = 5, 0
----> 2 x/y

ZeroDivisionError: integer division or modulo by zero

In [2]:
s = 'hello'
s[100]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-2-c9fa9df27c97> in <module>()
      1 s = 'hello'
----> 2 s[100]

IndexError: string index out of range

Try Except 处理器


In [3]:
x, y = 5, 0
try:
    x/y
except ZeroDivisionError:
    print 'error'


error

In [4]:
s = 'hello'
try:
    s[100]
except ZeroDivisionError:  # 捕获除0操作?
    print 'error'


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-d4d23922aa9f> in <module>()
      1 s = 'hello'
      2 try:
----> 3     s[100]
      4 except ZeroDivisionError:  # 捕获除0操作?
      5     print 'error'

IndexError: string index out of range

异常的继承关系


In [5]:
try:
    1/0
except ZeroDivisionError:
    print 'ZeroDivisionError catched'
except ArithmeticError:
    print 'ArithmeticError catched'


ZeroDivisionError catched

In [6]:
try:
    1/0
except ArithmeticError:
    print 'ArithmeticError catched'
except ZeroDivisionError:
    print 'ZeroDivisionError catched'


ArithmeticError catched

触发异常


In [7]:
raise


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-26814ed17a01> in <module>()
----> 1 raise

TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType

In [8]:
raise ZeroDivisionError


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-8-2e97f6491c44> in <module>()
----> 1 raise ZeroDivisionError

ZeroDivisionError: 

In [9]:
try:
    raise ZeroDivisionError
except ZeroDivisionError:
    print 'error'


error

In [10]:
try:
    raise "exception"
except "exception":
    print "catched"


/Users/heming03/python-env/lib/python2.7/site-packages/ipykernel_launcher.py:3: DeprecationWarning: catching of string exceptions is deprecated
  This is separate from the ipykernel package so we can avoid doing imports until
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-e89055c1e0be> in <module>()
      1 try:
----> 2     raise "exception"
      3 except "exception":
      4     print "catched"

TypeError: exceptions must be old-style classes or derived from BaseException, not str

Try/Catch/Else


In [12]:
try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print "Error: 没有找到文件或读取文件失败"
else:
    print "内容写入文件成功"
    fh.close()


内容写入文件成功

ELSE


In [13]:
try:
    print('no excpetion here')
except Exception:
    print('exception')
else:
    # 这里的代码只会在try语句里没有触发异常时运行,
    # 但是这里的异常将 *不会* 被捕获
    print('only run when no exception')
finally:
    print('print anyway')


no excpetion here
only run when no exception
print anyway

Finally


In [14]:
try:
    fh = open("testfile.notexist", "r")
    fh.write("这是一个测试文件,用于测试异常!!")
finally:
    print "Error: 没有找到文件或读取文件失败"


Error: 没有找到文件或读取文件失败
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-14-233938dce830> in <module>()
      1 try:
----> 2     fh = open("testfile.notexist", "r")
      3     fh.write("这是一个测试文件,用于测试异常!!")
      4 finally:
      5     print "Error: 没有找到文件或读取文件失败"

IOError: [Errno 2] No such file or directory: 'testfile.notexist'

In [15]:
try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
finally:
    print "Error: 没有找到文件或读取文件失败"


Error: 没有找到文件或读取文件失败

finally陷阱


In [16]:
def func():
    try:
        1/0
    except IndexError, e:
        print 'index error'
    finally:
        print 'finally missed'
        return

In [17]:
func()

# 为什么异常消失了?


finally missed

自定义异常


In [ ]:
class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
try:
    raise MyError(2*2)
except MyError as e:
    print 'My exception occurred, value:', e.value

断言


In [18]:
assert 1==1

In [19]:
assert 1==0


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-19-ab8cbedd7149> in <module>()
----> 1 assert 1==0

AssertionError: 

In [20]:
assert 3<2


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-20-f0d11256d59d> in <module>()
----> 1 assert 3<2

AssertionError: 

In [21]:
assert True

In [22]:
# 异常参数
assert True, 'error...'

With/As


In [23]:
with open('nothing.txt','w') as f:
    f.write('a')
    print 2/0
    print 'continue'


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-23-ccb3eae027b7> in <module>()
      1 with open('nothing.txt','w') as f:
      2     f.write('a')
----> 3     print 2/0
      4     print 'continue'

ZeroDivisionError: integer division or modulo by zero

环境管理协议


In [24]:
class Open:
    def __init__(self,filepath):
        self.f = filepath

    def write(self):
        pass

    def __enter__(self):
        print "出现with语句,对象会调用我"
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print "with结束之后,会执行我"
        # return True  #返回值为正,with里面抛出异常时,程序不会退出,会执行with代码块,后面的代码

In [25]:
with Open('1.txt') as fp:
    fp.write()
    1/0


出现with语句,对象会调用我
with结束之后,会执行我
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-25-893a3bf9f599> in <module>()
      1 with Open('1.txt') as fp:
      2     fp.write()
----> 3     1/0

ZeroDivisionError: integer division or modulo by zero

异常和相关模块


In [26]:
import traceback
import inspect
try:
    1/0
except:
    traceback.print_exc()
    print traceback.format_exc()
    # print inspect.stack()


Traceback (most recent call last):
  File "<ipython-input-26-47e0edf57631>", line 4, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

Traceback (most recent call last):
  File "<ipython-input-26-47e0edf57631>", line 4, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

In [27]:
import sys
try:
    1/0
except:
    tp,val,td = sys.exc_info()
    print tp,":",val


<type 'exceptions.ZeroDivisionError'> : integer division or modulo by zero

In [ ]: