这里只分析几个可能会常用到的魔法方法,像__new__这种不常用的,用来做元类初始化的或者是__init__这种初始化使用的 每个人都会用的就不介绍了。
其实每个魔法方法都是在对内建方法的重写,和做像装饰器一样的行为。理解这个道理 再尝试去理解每个细节装饰器会比较方便。
关于**str和repr**:
直接上例子:
class Test(object):
def __init__(self, world):
self.world = world
def __str__(self):
return 'world is %s str' % self.world
def __repr__(self):
return 'world is %s repr' % self.world
t = Test('world_big')
print str(t)
print repr(t)output:
world is world_big strworld is world_big repr
其实__str__相当于是str()方法 而__repr__相当于repr()方法。str是针对于让人更好理解的字符串格式化,而repr是让机器更好理解的字符串格式化。
其实获得返回值的方法也很好测试,在我们平时使用ipython的时候,在不使用print直接输出对象的时候,通常调用的就是repr方法,这个时候改写repr方法可以让他方便的输出我们想要知道的内容,而不是一个默认内容。
关于**hash__和__dir😗*
其实在实际应用中写了这么久python,也没有用到需要这两个方法出现的地方,但是在有些库里面是有看到过。
__hash__是hash()方法的装饰器版本,而__dir__是dir()的装饰器版本。
上代码展示一下__hash__用法:
'''
class Test(object):
def __init__(self, world):
self.world = world
x = Test('world')
p = Test('world')
print hash(x) == hash(p)
print hash(x.world) == hash(p.world)
class Test2(object):
def __init__(self, song):
self.song = song
def __hash__(self):
return 1241
x = Test2('popo')
p = Test2('janan')
print x, hash(x)
print p, hash(p)output:
FalseTrue