python特殊函数 __call__() 等于 self()

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 friend is %s...' % friend)
        
    def my(self):
        self('test')




# 对象的定义
p = Person('Bob', 'male')

# 第0种情况:通过 调用本身__call__()来执行
p.__call__('test')

print('--------------------')

# 第1种情况:通过 对象后加 括号 来调用__call__()
p('test')

print('--------------------')

# 第2种情况:通过 内部 self() 来调用 __call__()
p.my()

结果如下:

My name is Bob...
My friend is test...
--------------------
My name is Bob...
My friend is test...
--------------------
My name is Bob...
My friend is test...

你可能感兴趣的:(python,开发语言)