Python中的__init__/__new__/__call_

2018-06-12  本文已影响0人  JM68

    class Foo(object):

        # 初始化实例的变量,当实例被__new__创建
        def __init__(self, name):
            self.name = name
            print('%s的__init__' % self.name)

        # __new__用于创建对象的实例
        def __new__(cls, *args, **kwargs):
            print('__new__')
            return object.__new__(cls)

        # 将对象实例作为函数被调用
        def __call__(self, a, b):
            print('__call__')
            return '%s %s' % (a, b)


    def main():
        a = Foo("a")
        print(a('hello', 'world'))


    if __name__ == '__main__':
        main()

代码的运行结果:

__new__
a的__init__
__call__
hello world
上一篇下一篇

猜你喜欢

热点阅读