Python学习,python的魔法方法

这里只分析几个可能会常用到的魔法方法,像__new__这种不常用的,用来做元类初始化的或者是__init__这种初始化使用的 每个人都会用的就不介绍了。

其实每个魔法方法都是在对内建方法的重写,和做像装饰器一样的行为。理解这个道理 再尝试去理解每个细节装饰器会比较方便。

关于**strrepr**:

直接上例子:

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值