7种可调用对象的方法

### 函数后的()其实是调用运算符,任何可以添加()的为可调用对象
# 1.用户定义的函数:使用def语句或lambda表达式创建
# 2.内置函数:如len
# 3.内置方法:如dic.get,底层有c语言实现
# 4.方法:在类定义体中的函数
# 5.类: 运行时候通过__new__创建新对象,然后__init__完成初始化,本质还是在调用函数
# 6. 类的实例:如果类定义了__call__,那么它的实例可以作为函数调用,表现像个函数
# 7. 生成器函数:使用yield关键字的函数或方法,返回生成器对象
def test():
    print('this is a test')
test()  # 函数的调用符号:()
this is a test
type(test)
function
print(type(test))
<class 'function'>
print(type(len))
<class 'builtin_function_or_method'>
print(type(set))
<class 'type'>
print(type(dict))
<class 'type'>
class Test:
    def do(self):
        print('this is test')

    def __call__(self):
        return self.do()
t = Test()
t.do()
this is test

猜你喜欢

转载自blog.51cto.com/13118411/2120058
今日推荐