html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video { margin: 0; padding: 0; border: 0 }
body { font-family: Helvetica, arial, freesans, clean, sans-serif; font-size: 14px; line-height: 1.6; color: #333; background-color: #fff; padding: 20px; max-width: 960px; margin: 0 auto }
body>*:first-child { margin-top: 0 !important }
body>*:last-child { margin-bottom: 0 !important }
p,blockquote,ul,ol,dl,table,pre { margin: 15px 0 }
h1,h2,h3,h4,h5,h6 { margin: 20px 0 10px; padding: 0; font-weight: bold }
h1 tt,h1 code,h2 tt,h2 code,h3 tt,h3 code,h4 tt,h4 code,h5 tt,h5 code,h6 tt,h6 code { font-size: inherit }
h1 { font-size: 28px; color: #000 }
h2 { font-size: 24px; border-bottom: 1px solid #ccc; color: #000 }
h3 { font-size: 18px }
h4 { font-size: 16px }
h5 { font-size: 14px }
h6 { color: #777; font-size: 14px }
body>h2:first-child,body>h1:first-child,body>h1:first-child+h2,body>h3:first-child,body>h4:first-child,body>h5:first-child,body>h6:first-child { margin-top: 0; padding-top: 0 }
a:first-child h1,a:first-child h2,a:first-child h3,a:first-child h4,a:first-child h5,a:first-child h6 { margin-top: 0; padding-top: 0 }
h1+p,h2+p,h3+p,h4+p,h5+p,h6+p { margin-top: 10px }
a { color: #4183C4; text-decoration: none }
a:hover { text-decoration: underline }
ul,ol { padding-left: 30px }
ul li>:first-child,ol li>:first-child,ul li ul:first-of-type,ol li ol:first-of-type,ul li ol:first-of-type,ol li ul:first-of-type { margin-top: 0px }
ul ul,ul ol,ol ol,ol ul { margin-bottom: 0 }
dl { padding: 0 }
dl dt { font-size: 14px; font-weight: bold; font-style: italic; padding: 0; margin: 15px 0 5px }
dl dt:first-child { padding: 0 }
dl dt>:first-child { margin-top: 0px }
dl dt>:last-child { margin-bottom: 0px }
dl dd { margin: 0 0 15px; padding: 0 15px }
dl dd>:first-child { margin-top: 0px }
dl dd>:last-child { margin-bottom: 0px }
pre,code,tt { font-size: 12px; font-family: Consolas, "Liberation Mono", Courier, monospace }
code,tt { margin: 0 0px; padding: 0px 0px; white-space: nowrap; border: 1px solid #eaeaea; background-color: #f8f8f8 }
pre>code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent }
pre { background-color: #f8f8f8; border: 1px solid #ccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px }
pre code,pre tt { background-color: transparent; border: none }
kbd { background-color: #DDDDDD; background-image: linear-gradient(#F1F1F1, #DDDDDD); background-repeat: repeat-x; border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD; border-style: solid; border-width: 1px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; line-height: 10px; padding: 1px 4px }
blockquote { border-left: 4px solid #DDD; padding: 0 15px; color: #777 }
blockquote>:first-child { margin-top: 0px }
blockquote>:last-child { margin-bottom: 0px }
hr { clear: both; margin: 15px 0; height: 0px; overflow: hidden; border: none; background: transparent; border-bottom: 4px solid #ddd; padding: 0 }
table th { font-weight: bold }
table th,table td { border: 1px solid #ccc; padding: 6px 13px }
table tr { border-top: 1px solid #ccc; background-color: #fff }
table tr:nth-child(2n) { background-color: #f8f8f8 }
img { max-width: 100% }
__setitem__,__getitem__,__delitem__
这三个方法和__setattr__,__getattr__,__delattr__类似,都是设定,获取,删除时触发,不同的是这三个方法触发的情况是通过字典键值对赋值的方式.
class Foo:
def __init__(self,name):
self.name=name
def __getitem__(self, item):
print(self.__dict__[item])
def __setitem__(self, key, value):
self.__dict__[key]=value
def __delitem__(self, key):
print(‘del obj[key]时,我执行‘)
self.__dict__.pop(key)
def __delattr__(self, item):
print(‘del obj.key时,我执行‘)
self.__dict__.pop(item)
f1=Foo(‘sb‘)
f1[‘age‘]=18
f1[‘age1‘]=19
del f1.age1
del f1[‘age‘]
f1[‘name‘]=‘alex‘
print(f1.__dict__)
__str__,__repr__,__format__
往往我们直接打印一个对象的时候,返回的是一个__str__,__repr__是实现对象的字符串显示
自定制格式化字符串__format__
#_*_coding:utf-8_*_
__author__ = ‘Linhaifeng‘
format_dict={
‘nat‘:‘{obj.name}-{obj.addr}-{obj.type}‘,#学校名-学校地址-学校类型
‘tna‘:‘{obj.type}:{obj.name}:{obj.addr}‘,#学校类型:学校名:学校地址
‘tan‘:‘{obj.type}/{obj.addr}/{obj.name}‘,#学校类型/学校地址/学校名
}
class School:
def __init__(self,name,addr,type):
self.name=name
self.addr=addr
self.type=type
def __repr__(self):
return ‘School(%s,%s)‘ %(self.name,self.addr)
def __str__(self):
return ‘(%s,%s)‘ %(self.name,self.addr)
def __format__(self, format_spec):
# if format_spec
if not format_spec or format_spec not in format_dict:
format_spec=‘nat‘
fmt=format_dict[format_spec]
return fmt.format(obj=self)
s1=School(‘oldboy1‘,‘北京‘,‘私立‘)
print(‘from repr: ‘,repr(s1))
print(‘from str: ‘,str(s1))
print(s1)
‘‘‘
str函数或者print函数--->obj.__str__()
repr或者交互式解释器--->obj.__repr__()
如果__str__没有被定义,那么就会使用__repr__来代替输出
注意:这俩方法的返回值必须是字符串,否则抛出异常
‘‘‘
print(format(s1,‘nat‘))
print(format(s1,‘tna‘))
print(format(s1,‘tan‘))
print(format(s1,‘asfdasdffd‘))
__slots__限制属性
如果要限制添加的属性,例如,Student类只允许添加 name、gender和score 这3个属性,就可以利用Python的一个特殊的__slots__来实现。
class Student(object):
__slots__ = (‘name‘, ‘gender‘, ‘score‘)
def __init__(self, name, gender, score):
self.name = name
self.gender = gender
self.score = score
__slots__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。
__next__和__iter__实现迭代器协议
class Range:
"自定义类模仿range函数"
def __init__(self,s_num,e_num,step=1):
self.s_num = s_num
self.e_num = e_num
self.step=step
def __iter__(self):
return self
def __next__(self):
if self.s_num==self.e_num:
raise StopIteration
n = self.s_num
self.s_num+=1*self.step
return n
def __del__(self):
print("dadada")
f = Range(2,20,2)
for i in f :
print(i)
__doc__,描述信息
class Foo:
‘我是描述信息‘
pass
print(Foo.__doc__
__del__,析构方法,当对象在内存中被释放时,自动触发执行。
class Foo:
def __del__(self):
print(‘执行我啦‘)
f1=Foo()
del f1
print(‘------->‘)
#输出结果
执行我啦
------->
注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。
__enter__和__exit__
为了对象兼容 with...as 语句,必须在这个对象的类中声明enter和exit方法
当一个对象被用作上下文管理器时:
__enter__ 方法将在进入代码块前被调用。
__exit__ 方法则在离开代码块之后被调用(即使在代码块中遇到了异常)。
class My_open:
def __init__(self, filename, mode):#接受参数
self.filename = filename
self.mode = mode
def __enter__(self):#打开文件是会运行__enter__
self.openedFile = open(self.filename, self.mode)#获取真实文件句柄
return self.openedFile#返回句柄
def __exit__(self, exc_type, exc_val, exc_tb):#文件关闭时会运行__exit__
self.openedFile.close()
"""此处如果不对exc_type, exc_val, exc_tb进行处理的话,with下的程序出错了就会报错
可以在这里加上处理机制,如果返回非False的值就不会报错了"""
def __getattr__(self, item):#其余的方法还是直接使用原来的
return getattr(self,item)
with My_open("a.txt", "w+") as writer:
writer.write("11111111111111")
__call__,对象后面加括号,触发执行
注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 call 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
class Fib(object):
"求一定长度的斐波那契数列"
def __call__(self, num):
l = []
a,b = 0,1
for i in range(num):
l.append(a)
a,b=b,a+b
return l
f = Fib()
print (f(10))