python类参数self使用示例

WBOY
Release: 2016-06-16 08:45:12
Original
1165 people have browsed it

复制代码 代码如下:

#coding:utf-8
"""
__new__和__init__到底是怎么一回事,看下面的代码
如果类没有定义__new__方法,就从父类继承这个__new__方法。
__new__先于__init__执行,类带括号调用时,发生这样的一件事,
先调用类的__new__方法,放回该类的实例对象,这个实例对象就是__init__方法的第一个参数。
请看代码中tmp,self,p的内存地址都是一样的,都是类的实例对象。
"""

class Foo(object):
    def __new__(cls, *args, **kwargs):
        """如果不覆盖这个__new__方法,也就是说不写这个__new__方法,类会从object
        继承__new__方法完成返回值实例对象
        """
        print "__new__方法先被调用"
        tmp = super(Foo,cls).__new__(cls,*args, **kwargs)
        print id(tmp)
        print type(tmp)
        print isinstance(tmp,Foo)
        print issubclass(type(tmp),Foo)
        return tmp

    def __init__(self):
        """self是python默认传的值,该值是调用__new__的返回值"""
        print "__init__被调用"
        print id(self)


p = Foo()
print id(p)
print type(p)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!