python 类 __call__

2021-07-09 08:05

阅读:724

标签:self   bsp   nbsp   int   __init__   class   object   code   括号   

 

__call__ 对象后面加括号,触发执行。

即:对象() 或者 类()()

 

class dog(object):


    def __init__(self,name):
        self.name = name

    def eat(self):
        print("%s is eating %s" % (self.name,ss))

    def talk(self):
        print("%s is taking" % self.name)

    def __call__(self, *args, **kwargs):
        print("you are ok?", args, kwargs)



d = dog("jianlin")
d()
d(1,2,3,name="mike")

‘‘‘
you are ok? () {}
you are ok? (1, 2, 3) {‘name‘: ‘mike‘}
‘‘‘

另外一种实现

class dog(object):


    def __init__(self,name):
        self.name = name

    def eat(self):
        print("%s is eating %s" % (self.name,ss))

    def talk(self):
        print("%s is taking" % self.name)

    def __call__(self, *args, **kwargs):
        print("you are ok?", args, kwargs)



dog("jianlin")()

# you are ok? () {}

 

python 类 __call__

标签:self   bsp   nbsp   int   __init__   class   object   code   括号   

原文地址:https://www.cnblogs.com/mingerlcm/p/8470030.html


评论


亲,登录后才可以留言!