AIHGF

Python - __call__ 函数
Python 创建 class 类时,如果定义了 call() 方法,则,实例化该 class 类时,实例名() ...
扫描右侧二维码阅读全文
16
2018/10

Python - __call__ 函数

Python 创建 class 类时,如果定义了 call() 方法,则,实例化该 class 类时,实例名() 即为调用 call() 的方法.

call() 实现了将 class 类实例转变成可调用对象.

Demo1:

class Demo_Person(object):
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender
        
    def __call__(self, words):
        print "My name is %s..." % self.name
        print "Hello: ", words

if __name__ == "__main__":
    demo_person = Demo_Person("HGF", "male")
    demo_person("Welcome to aiuai.cn!")

输出:

My name is HGF...
Hello:  Welcome to aiuai.cn!

Demo2: - 斐波那契数列

class Fib(object):
    def __init__(self):
        print "Fib Demo."
        
    def __call__(self,num):
        a,b = 0,1;
        self.l = []
        
        for i in range (num):
            self.l.append(a)
            a,b= b,a+b
        return self.l
    
if __name__ == "__main__":
    fib = Fib()
    print fib(10)

输出:

Fib Demo.
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Last modification:October 16th, 2018 at 11:03 am

Leave a Comment