python3 和python2 调用父类构造方法写法区别

1. python3 和python2 调用父类构造方法写法区别

前一段时间,把之前的一个项目迁移到python3
发现了很多不同的地方.我这里简单说明了,构造方法的不同 之后可能会继续更新不同. 主要针对项目迁移进行总结,反思. 这里就当做笔记.

python3 代码 调用父类的构造方法

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: Frank 
@contact: frank.chang@shoufuyou.com
@file: py2topy3.py
@time: 2018/7/7 上午7:09

## python3 代码 

"""

import threading
import queue

_sentinel = object()


class Consumer(threading.Thread):
    """
    消费者线程类
    """

    def __init__(self, name, queue):
        super().__init__(name=name)
        self.queue = queue

    def run(self):
        while True:
            values = self.queue.get(timeout=None)

            if values is _sentinel:
                self.queue.put(values)
                break
            ##process  values
            ##xxx
            print('consume is consuming data {}'.format(values))

        print("{} finished".format(self.getName()))


if __name__ == '__main__':
    q = queue.Queue()
    concumser = Consumer('consumer', q)

    print(concumser)

        

2 python2.7 调用父类的构造方法

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: Frank 
@contact: frank.chang@shoufuyou.com
@file: 3.py
@time: 2018/7/7 上午7:05

"""

import Queue
import threading

# 哨兵
_sentinel = object()


class Consumer(threading.Thread):
    """
    消费者线程类
    """

    def __init__(self, name, queue):
        super(Consumer, self).__init__(name=name)
        self.queue = queue

    def run(self):
        while True:
            values = self.queue.get(timeout=None)

            if values is _sentinel:
                self.queue.put(values)
                break
            ##process  values
            ##xxx
            print('consume is consuming data {}'.format(values))

        print("{} finished".format(self.getName()))


if __name__ == '__main__':
    q = Queue.Queue()
    concumser = Consumer('consumer', q)
    print(concumser)

区别

主要区别是 super 的变化,

python3 中直接 super().init() 中 super 不需要传递任何参数,直接可以调用父类的构造方法

python2 中 super(Consumer, self).init(), 需要传两个参数一个是类名, 一个是self. 这样比较麻烦,很容易混淆. 但是python3 这里处理的比较好了.

可以看下这个文档  https://docs.python.org/3/library/functions.html#super

顺便提一下, python2 和python3 中 quque 名称换了,python3 用的是小写 作为模块名称.

参考文档

What’s New In Python 3.0

分享快乐,留住感动.2018-07-07 07:57:45 --frank
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值