zoukankan      html  css  js  c++  java
  • python的__call__,__new__,__init__

    new

    用于创建对象,是一个静态方法,第一个参数是cls,该方法必须返回一个对象实例,可以return父类__new__()出来的实例,也可以直接将object的__new__()出来的实例返回

    class Foo(object):
          def __new__(cls, *args, **kwargs):
        	   print '__new__ method called'
               return object.__new__(cls, *args, **kwargs) # 必须返回对象实例,否则调用__init__方法
    obj = Foo() # 输出 __new__ method called
    

    init

    用于对象的初始化,每次调用__init__ 之前,都会先调用__new__

    class Foo(object):
    	def __new__(cls, *args, **kwargs):
        	print '__new__ method called'
        	return object.__new__(cls, *args, **kwargs) #A 必须返回对象实例,否则调用__init__方法
            def __init__(self, *args, **kwargs):
                print '__init__ method called'
    obj = Foo() # 先输出:__new__ method called ,再输出: __init__ method called# 注意:如果把 A 行注释,则不会输出 __init__ method called, 因为没有对象实例返回,所以不会调用__init__方法
    

    call

    对象可call,是对象,而不是类

    class Foo(object):
    	def __new__(cls, *args, **kwargs):
    		print '__new__ method called'
            return object.__new__(cls, *args, **kwargs) #A 必须返回对象实例,否则调用__init__方法
        def __init__(self, *args, **kwargs):
        	print '__init__ method called'
        def __call__(self, *args, **kwargs):
        	print '__call__ method called'obj = Foo() # 先输出:__new__ method called ,再输出: __init__ method called
    obj()       # 输出: __call__ method called
    

    取自:http://www.tang-lei.com/2018/08/30/python-详解-new-init-call-方法/

  • 相关阅读:
    python之private variable
    python实例、类方法、静态方法
    python常用option
    access
    FD_CLOEXEC
    fork后父子进程文件描述问题
    split
    信号
    kill
    进程组&Session
  • 原文地址:https://www.cnblogs.com/zfb123-/p/13321180.html
Copyright © 2011-2022 走看看