现在的位置: 首页 > 综合 > 正文

python类常见函数重载函数定义及举例(不断更新)

2018年05月13日 ⁄ 综合 ⁄ 共 669字 ⁄ 字号 评论关闭

Last Update: 2013-4-9

openxmpp@163.com

1) __class__

2)  __cmp__

3)  __contains__

4) __delattr__

5)  __delitem__

6)  __dict__

7)  __doc__

8) __len__

9)  __repr__

10) __call__

重载此方法的,调用callable返回True,对于类来说,一直是callable的,但对于对象来说,如果没有实现__call__方法,则不是callable的,否则是callable的

11) __dir__

>>>classShape(object):def
__dir__(self):

                return [’area’, ’perimeter’, ’location’]

>>>s=Shape()
>>>dir(s)
[’area’, ’perimeter’, ’location’] 

12)__nonzero__

当与 if 进行比较判断时,如果类重载了__nonzero__方法,则会根据该方法来进行判断,否则默认返回True
      
       

class MyClass:
    def __init__(self,value):
        self.mValue = value
    def __nonzero__(self):
        if self.mValue % 2 :
            return False
        else:
            return True

a1 = MyClass(1)
a2 = MyClass(2)

if a1:
    print "a1 is not None"  #a1为奇数,不输出

if a2:
    print "a2 is not none"  #a2为偶数,此句输出


抱歉!评论已关闭.