python一些定制方法(函数)

__str__() __call__() __repr__()方法

>>> class Student(object):
    def __init__(self, name):
        self.name = name

    def __call__(self):
        print('My name is %s.' % self.name)
    def __str__(self):
	return 'I am a print call for name:%s !'%self.name
    def __repr__(self):
	return 'I am a print var value for name:%s !'%self.name

>>> s = Student('lucy')
>>> s     //call __repr__()
I am a print var value for name:lucy !
>>> s()   // call __call__()
My name is lucy.
>>> print s    //call __str__()
I am a print call for name:lucy !

  



 __str__是调用print 打印,
__repr__是直接写变量时打印的

__iter__()方法


如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法

__getitem__()方法


要表现得像list那样按照下标取出元素,需要实现__getitem__()方法

__getattr__()方法


那就是写一个__getattr__()方法,动态返回一个属性

class Student(object):

    def __init__(self): self.name = 'Michael' def __getattr__(self, attr): if attr=='score': return 99
  raise
AttributeError('\'Student\' object has no attribute \'%s\'' % attr) //调用不存在的属性是,抛出
>>> s = Student()
>>> s.name
'Michael'
>>> s.score
99

本节介绍的是最常用的几个定制方法,还有很多可定制的方法,请参考Python的官方文档
http://docs.python.org/2/reference/datamodel.html#special-method-names













转载于:https://www.cnblogs.com/if-then/p/7353249.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值