首页 > 编程语言 > 详细

python 定义class时的内置方法

时间:2018-08-28 14:53:55      阅读:254      评论:0      收藏:0      [点我收藏+]

__contains__():对类实例使用in ,not in操作时调用

class A(object):

    def __init__(self,num):

        self.num=num

    def __contains__(self,item):

        print(‘__contains__: %s is in ?‘ % item )

        if item < self.num and item >= 0 :

            return True

        else :

            return False

if __name__==‘__main__‘:

    if 3 in A(10):

        print(‘True‘)

    else:

        print(‘False‘)

输出:

__contains__: 3 is in ?

True

 

__call__():像函数一样调用类实例时使用的方法

class Person(object):

    def __init__(self,name,gender):

        self.name=name

        self.gender=gender

    def __call__(self,friend):

        print(‘My name is %s ...‘ % self.name)

        print(‘My friends is %s ...‘ % friend)

p=Person(‘Bob‘,‘male‘)

p(‘Tim‘)

输出:

My name is Bob ...

My friends is Tim ...

python 定义class时的内置方法

原文:https://www.cnblogs.com/Ting-light/p/9548090.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!