首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

Python _init_ _new_ 有跟区别

2012-10-15 
Python __init__ __new__ 有和区别如题另外,这两个方法的有什么作用在Python里面有很多__开头的方法,他们

Python __init__ __new__ 有和区别
如题
另外,这两个方法的有什么作用
在Python里面有很多__开头的方法,他们一般是些什么方法?
Python的面向对象我还像有或多的困惑,怎么样才能理解清楚?能否有人传授点秘诀或是给个链接?

[解决办法]
一般很少情框下用到__new__, 
__new__ 比 __init__ 优先

Python code
class A(object):    def __init__(self):        print ("__init__")    def __new__(self):        print ("__new__")A()  $ python test.py __new__
[解决办法]
__new__一般是用于继承内置类的,返回值是一个对象,__init__只做一些初始化工作,没有返回值
[解决办法]
__new__:创建对象时调用,返回当前对象的一个实例相当于java里面的构造器差不多

__init__:创建完对象后调用,对当前对象的实例的一些初始化,无返回值

如果重写了__new__而在__new__里面没有调用__init__那么__init__将不起作用。

可以这样理解,默认是创建(__new__),然后调用__init__,所以一楼的例子举错了。

[解决办法]
楼上说的没错,先谢谢啦


如果 __new__ 有return instance 的话,应该是等於call 了__init__
 
http://docs.python.org/reference/datamodel.html#object.__new__

Python code
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. 

热点排行