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]:
In [3]:
# 类内的赋值语句会创建类的属性
# 类属性提供对象的状态和行为
class B:
x = 10
def getname(self):
print id(self), type(self)
print B.x
print B.getname
In [5]:
a = A()
print a
In [6]:
b = B()
print id(b)
b.getname()
In [14]:
dir(a)
print A.__doc__
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)
In [21]:
p2 = Person("kate", 19)
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()
In [24]:
del p
In [25]:
# 作用域
def call_one():
q = Person()
return None
call_one()
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
In [33]:
p
Out[33]:
In [36]:
p1 = eval(repr(p))
In [37]:
class stepper:
def __getitem__(self,i):
return self.data[i]
X = stepper()
X.data="Spam"
print X[1]
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
In [40]:
class Chinese(Person):
pass
In [41]:
c = Chinese()
print c.name
In [42]:
c.show()
print c
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()
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()
In [48]:
#TestClass.callFunc()
TestClass.callStatic()
TestClass.callClass()
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__
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()
In [51]:
class A(object):
__slots__ = ('name', 'age')
class A1():
__slots__ = ('name', 'age')
a1 = A1()
a = A()
a1.name1 = "a1"
a.name1 = "a"
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
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 # 这样就可以访问了,伪私有变量
In [58]:
class A(object):
def __func(self):pass
print A.__dict__
a = A()
a._A__func()
In [1]:
x, y = 5, 0
x/y
In [2]:
s = 'hello'
s[100]
In [3]:
x, y = 5, 0
try:
x/y
except ZeroDivisionError:
print 'error'
In [4]:
s = 'hello'
try:
s[100]
except ZeroDivisionError: # 捕获除0操作?
print 'error'
In [5]:
try:
1/0
except ZeroDivisionError:
print 'ZeroDivisionError catched'
except ArithmeticError:
print 'ArithmeticError catched'
In [6]:
try:
1/0
except ArithmeticError:
print 'ArithmeticError catched'
except ZeroDivisionError:
print 'ZeroDivisionError catched'
In [7]:
raise
In [8]:
raise ZeroDivisionError
In [9]:
try:
raise ZeroDivisionError
except ZeroDivisionError:
print 'error'
In [10]:
try:
raise "exception"
except "exception":
print "catched"
In [12]:
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print "Error: 没有找到文件或读取文件失败"
else:
print "内容写入文件成功"
fh.close()
In [13]:
try:
print('no excpetion here')
except Exception:
print('exception')
else:
# 这里的代码只会在try语句里没有触发异常时运行,
# 但是这里的异常将 *不会* 被捕获
print('only run when no exception')
finally:
print('print anyway')
In [14]:
try:
fh = open("testfile.notexist", "r")
fh.write("这是一个测试文件,用于测试异常!!")
finally:
print "Error: 没有找到文件或读取文件失败"
In [15]:
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
finally:
print "Error: 没有找到文件或读取文件失败"
In [16]:
def func():
try:
1/0
except IndexError, e:
print 'index error'
finally:
print 'finally missed'
return
In [17]:
func()
# 为什么异常消失了?
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
In [20]:
assert 3<2
In [21]:
assert True
In [22]:
# 异常参数
assert True, 'error...'
In [23]:
with open('nothing.txt','w') as f:
f.write('a')
print 2/0
print 'continue'
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
In [26]:
import traceback
import inspect
try:
1/0
except:
traceback.print_exc()
print traceback.format_exc()
# print inspect.stack()
In [27]:
import sys
try:
1/0
except:
tp,val,td = sys.exc_info()
print tp,":",val
In [ ]: