首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
  • 您找到你想要的搜索结果了吗?
    是的
    没有找到

    Python中_new_方法详解及使用

    _new_的作用 在python中_new_方法与_init_方法类似,但是如果两都存在那么_new_闲执行。 在基础类object中,_new_被定义成了一个静态方法,并且需要传递一个参数cls。Cls表示需实例化的类,此参数在实例化时由Python解析器自动提供。 new()是在新式类中新出现的方法,它作用在构造方法init()建造实例之前,可以这么理解,在Python 中存在于类里面的构造方法init()负责将类的实例化,而在init()调用之前,new()决定是否要使用该init()方法,因为new()可以调用其他类的构造方法或者直接返回别的对象来作为本类 的实例。  New(方法的特性) new()方法是在类准备将自身实例化时调用。  new()方法始终都是类的静态方法,即使没有被加上静态方法装饰器。 实例 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 Python3和python2中_new_使用不同 Python2的写法 注意python版本大于等于2.7才支持 class Singleton(object):     def __new__(cls,args, *kwargs):         if not hasattr(cls,'_inst'):             print(cls)             cls._inst = super(Singleton, cls).__new__(cls,args,*kwargs)         return cls._inst Python3的写法 class Singleton(object):     def __new__(cls,args, *kwargs):         if not hasattr(cls,'_inst'):             print(cls)             cls._inst = super(Singleton, cls).__new__(cls)         return cls._inst 如果Python3的写法跟Python2写法一样,那么倒数第二行会报错"TypeError: object() takes no parameters"

    02

    002:Python爬虫Urllib库全面分析

    Python中有一个功能强大,用于操作URL,并且在爬虫中经常使用的库、就是Urllib库。 (在python2的时候,有Urllib库,也有Urllib2库。Python3以后把Urllib2合并到了Urllib中) 合并后,模块中有很多的位置变动。我在这里先介绍一些常用的改动。 Python2: import urllib2 >>>>>Python3:import urllib.request,urllib.error Python2:import urllib >>>>>Python3:import urllib.request,urllib.error,urllib.parse Python2:import urlparse >>>>>Python3:import urllib.parse Python2:urllib2.urlopen >>>>>Python3:urllib.request.urlopen Python2:urllib.urlencode >>>>>Python3:urllib.request.urlencode Python2:urllib.quote >>>>>Python3:urllib.request.quote Python2:cookielib.CookieJar >>>>>Python3:http.CookieJar Python2:urllib.Request >>>>>Python3:urllib.request.Request 以上是Urllib中常用命令的一些变动。如果之前没有Urllib的基础也没关系,本文后面会详细介绍这些代码的具体应用,以及其实现的各种功能。

    01

    扫码

    添加站长 进交流群

    领取专属 10元无门槛券

    手把手带您无忧上云

    扫码加入开发者社群

    相关资讯

    热门标签

    活动推荐

      运营活动

      活动名称
      广告关闭
      领券