`

Python __new__ 、__init__、 __call__

阅读更多
Contains:
  • __new__: 创建对象时调用,返回当前对象的一个实例
  • __init__:创建完成对象后调用,对当前对象的实例的一些初始化,无返回值
  • __call__:

一、__init__通过此方法我们可以顶一个对象的初始操作。
但是当我新建一个类的实例的时候,__init__并不是第一个被调用的,实际上,还有一个叫做__new__的方法,来构造这个实例。然后在给开始创建的初始化函数传递参数。


二、__new__   
   
    @staticmethod # known case of __new__
    def __new__(cls, *more): # known special case of object.__new__

        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """

        pass

__new__方法相当不常用,但是它有自己的特性,特别是当继承一个不可变的类型比如一个tuple或者string.
Q:可是什么时候使用__new__?
难道是这个吗?特别是当继承一个不可变的类型比如一个tuple或者string.
引用

object.__new__(cls[, …])
Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).
Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super(currentclass, cls).__new__(cls[, ...])with appropriate arguments and then modifying the newly-created instance as necessary before returning it
If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().
If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.
__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

三、__call__

引用
Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).


这个方法可以让类的实例的行为表现的像函数一样,你可以调用他们,讲一个函数当做一个参数传到另外一个函数中等等。
class Entity:

    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __call__(self, x, y):
        self.x = x
        self.y = y

entity = Entity(2,3)
print 'before __call__',(entity.x,entity.y)
entity.__call__(4,5)
print 'after __call__',(entity.x,entity.y)

result:
before __call__ (2, 3)
after __call__ (4, 5)

参考资料:
http://docs.python.org/2/reference/datamodel.html
http://stackoverflow.com/questions/8106900/new-and-init-in-python
http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init
http://www.wingide.com/psupport/python-manual/2.4/ref/customization.html
http://stackoverflow.com/questions/12971641/need-to-understand-the-flow-of-init-new-and-call?lq=1
http://pycoders-weekly-chinese.readthedocs.org/en/latest/issue6/a-guide-to-pythons-magic-methods.html
分享到:
评论

相关推荐

    浅谈python中的__init__、__new__和__call__方法

    主要给大家介绍了关于python中__init__、__new__和__call__方法的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友可以参考学习,下面来跟着小编一起看看吧。

    详解Python中的__new__、__init__、__call__三个特殊方法

    __call__ : 对象可call,注意不是类,是对象。 先有创建,才有初始化。即先__new__,而后__init__。 上面说的不好理解,看例子。 1.对于__new__ class Bar(object): pass class Foo(object): def __new__(cls, ...

    python中的__init__ 、__new__、__call__小结

    注意,这里的第一个参数是self即对象本身【注意和new的区别】3.__call__(self, *args, **kwargs) 如果类实现了这个方法,相当于把这个类型的对象当作函数来使用,相当于 重载了括号运算符  看具体的例子:复制代码...

    python3.6.5参考手册 chm

    What’s New in Python What’s New In Python 3.6 Summary – Release highlights New Features PEP 498: Formatted string literals PEP 526: Syntax for variable annotations PEP 515: Underscores in ...

    Python Cookbook, 2nd Edition

    Python Cookbook, 2nd Edition By David Ascher, Alex Martelli, Anna Ravenscroft Publisher : O'Reilly Pub Date : March 2005 ISBN : 0-596-00797-3 Pages : 844 Copyright Preface The ...

    Python学习笔记之常用函数及说明

    复制代码 代码如下:C.__init__(self[, arg1, …]) 构造器(带一些可选的参数)C.__new__(self[, arg1, …]) 构造器(带一些可选的参数);通常用在设置不变数据类型的子类。C.__del__(self) 解构器C.__str__(self) ...

    Python Cookbook英文版

    5.3 Calling a Superclass _ _init_ _ Method if It Exists 5.4 Calling a Superclass Implementation of a Method 5.5 Implementing Properties 5.6 Implementing Static Methods 5.7 Implementing Class ...

    LuaBind 源码 (Lua增强库)

    call_function()函数有两个重载版本.一个是根据函数的名字来调用函数, 另一个是调用一个可以作为函数调用的Lua值. 使用函数名来调用的版本只能调用Lua全局函数. "..."代表传递给Lua函数的 可变个数的参数. 这使得你...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. ...

    smaliemu:小型模拟器

    Smaliemu 这是的PY3版本。 安装 pip install smaliemu 用法 from smaliemu.emulator import Emulator emu = Emulator() snippet = [ ...-><init>([B)V', 'return-object v0' ] ret = emu.call(snippet) pri

    imgurnode:用于与 Imgur API 交互的简单 Express 服务器

    图像节点 用于与 Imgur API 交互的节点包。 这是官方 Python Imgur API imgurpython 的一个端口。 见: : ... // Call init to validate access token // Will refresh access token if refresh to

Global site tag (gtag.js) - Google Analytics