Eighteen, Python Object-oriented methods of magic

1. Comparison of class
class A(object):
def __init__(self,value):
self.value = value
def __eq__(self,other):
return self.value == other.value
def __ne__(self,other):
return self.value != other.value
def __gt__(self,other):
return self.value > other.value
def __lt__(self,other):
return self.value < other.value
def __ge__(self,other):
return self.value >= other.value
def __le__(self,other):
return self.value <= other.value
 
 
a = A(100)
b = A(200)
 
print ( a == b)
print ( a != b)
print ( a > b)
print ( a < b)
print ( a >= b)
print ( a <= b)
 
Note: __ cmp__ also for comparison, a> b returns 1, a <b returns -1, a = b returns 0
--------------------------------------------------------
--------------------------------------------------------
--------------------------------------------------------
2.__new__,__init__,__del__
__new__ method, which uses metaclass
__init__ method, constructor, used when the object is instantiated
__del__方法,简单理解为是一个析构函数,当一个对象被垃圾回收机制回收的时候,其实就是调用了该方法,可以在该方法中定义一些释放资源的操作,如文件的关闭,数据库连接的关闭等(用得不多)
 
3.__str__方法,定义了我们使用str方法直接print一个对象的行为:
class S(object):
def __init__(self,value):
self.a = value
self.b = value
def __str__(self):
return "a=%s b=%s" % (self.a,self.b)
value = S("hello")
print (value)
 
4.__repr__类似于__str__,不过__repr__ 返回的是机器可读的字符串,__str__返回的是人类可读的
 
5.__unicode__返回一个unicode的对象u'hello',类似于__str__方法。
 
6.__hash__,我们定义类的时候是不需要定义__hash__方法的,因为父类object已经定义过了
 
7.__getattr__方法,当一个实例有这个属性的时候直接返回,如果没有会调用该方法
class Test(object):
def __init__(self):
self.a = 1
def __getattr__(self,name):
print ("get attr %s" % name)
 
t = Test()
print t.a
 
t.b
运行返回结果为
1
get attr b
总结:__getattr__的作用就是,当我里面定义了a这个实例变量,我打印它的时候它的值就是a的值1,当我没有定义b这个实例变量的时候,我强行t.b如果没有__getattr__这个方法就会报错,但是如果有这个方法它就会将b赋值给变量name然后打印出来。
 
8.__enter__和__exit__,在IO的部分说过with语法,只要一个类实现了这个两个方法就可以使用with语法:
class W(object):
def __init__(self):
self.f = open('/tmp/text.txt','w')
def __enter__(self):
return self.f
def __exit__(self,*excinfo)
#该方法接受一个可变参数,出现异常的时候将异常传值给该参数,
#在该函数内根据异常可以做相应的处理
self.f.close()
with W() as f:
print (f.closed())#看这个时候text.txt有没有关闭
f.write("hello,world") #向文件中写一行内容
 
print f.closed()#再看这个时候text.txt有没有关闭
 
上例仅仅是个演示,演示了为什么我们可以使用with语法,它会自动关闭文件。
 
class W(object):
def __init__(self):
self.f = open('/tmp/text.txt','r')
def __enter__(self):
return self.f.readlines()
def __exit__(self,*excinfo)
self.f.close()
with W() as f:
for l in f:
print (l)
 
 

Guess you like

Origin www.cnblogs.com/steven9898/p/11329438.html
Recommended