zoukankan      html  css  js  c++  java
  • Python 内置方法new

    class Dog(object):
            def __new__(self):
                    print("i am new .")
    
            def __init__(self):
                    print("i am init .")
    
            def run(self):
                    print("runing .")
    
    
    
    
    dog = Dog()
    
    dog.run()
    
    #打印i am new.
    #执行run()方法失败
    #错误原因:没有生成dog对象,所以调用方法失败
    class Dog(object):
            #new方法中的参数是类对象参数,而不是类实体对象参数
            def __new__(cls):
                    print("i am new .")
                    #打印类对象的地址
                    print(id(cls))
                    #调用父类的方法,创建类实体对象
                    #new方法必须有返回值
                    return object.__new__(cls)
    
            def __init__(self):
                    print("i am init .")
    
            def run(self):
                    print("runing .")
    
    
    
    
    dog = Dog()
    
    dog.run()
    
    
    '''
    python类实体对象创建过程
    第一步:调用__new__创建对象
    第二步:将new方法的返回值传递给init方法
    第三步:返回类实体对象的引用
    
    
    '''
  • 相关阅读:
    rwkj 1337
    poj 1002
    map
    vector
    sort排序
    sort函数
    poj 2945
    poj2388
    rwkj 1422搜索(素数环)
    poj2503
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/9650985.html
Copyright © 2011-2022 走看看