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 用的是小写 作为模块名称.