Python中的__call__方法

class Person:
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

    def __call__(self, friend):
        print('My name is %s...' % self.name)
        print('My friend is %s...' % friend)

    def dome(self):
        print('My name is king')
p = Person('Tom','male')
p('li')  #当调用此类,并没有指定具体的函数时,调用__call__方法
# 把一个类像一个方法那样调用
# My name is Tom...
# My friend is li...

#/usr/bin/env python
class test:
    def __init__(self,a):
        self.a = a
    def __call__(self,b):
        c = self.a+b
        print(c)
    def display(self):
        print(self.a)

Test = test("This is test!")
Test.display()
Test("##Append something")
# This is test!
# This is test!##Append something

你可能感兴趣的:(python)