zoukankan      html  css  js  c++  java
  • Python 中__new__方法详解及使用

    1、__new__的作用

    在Python中new方法与init方法类似,但是如果两个都存在那么new闲执行。
    
    在基础类object中,new被定义成了一个静态方法,并且需要传递一个参数cls。
    Cls表示需要实例化的类,此参数在实例化时由Python解析器自动提供。
    
    new()是在新式类中新出现的方法,它作用在构造方法init()建造实例之前,可以这么理解,在Python 中存在于类里面的
    构造方法init()负责将类的实例化,而在init()调用之前,new()决定是否要使用该init()方法,因为new()可以调用其他类的
    构造方法或者直接返回别的对象来作为本类 的实例。


    2、new()方法的特性

    new()方法是在类准备将自身实例化时调用。
    
    new()方法始终都是类的静态方法,即使没有被加上静态方法装饰器;


    3、实例

    class Person(object):
      
        def __init__(self, name, age):
            self.name = name
            self.age = age
         
        def __new__(cls, name, age):
            if 0 < age < 150:
                return object.__new__(cls)
                # return super(Person, cls).__new__(cls)
            else:
                return None
      
        def __str__(self):
            return '{0}({1})'.format(self.__class__.__name__, self.__dict__)
      
    
    print(Person('Tom', 10))
    print(Person('Mike', 200))


    结果:

    Person({'age': 10, 'name': 'Tom'})
    
    None
  • 相关阅读:
    Web开发细节搜集
    excel设置单元格为文本
    网页QQ唤起
    .net提高文章
    代码重构学习
    js的undefined怎么判断
    微软.net一些类的源码
    FineMessBox的js依赖导致错误Uncaught ReferenceError: addEvent is not defined
    [译转]深入理解LayoutInflater.inflate()
    java 和 Android Base64加密
  • 原文地址:https://www.cnblogs.com/weiyiming007/p/12552225.html
Copyright © 2011-2022 走看看