当前位置: 移动技术网 > IT编程>脚本编程>Python > python3 特色菜

python3 特色菜

2020年07月08日  | 移动技术网IT编程  | 我要评论

背景

最近项目遇到一个问题:一个开源的python3.7的工程需要在python2.7的环境下运行起来。别问我为什么没找到python2.7的源码,问就是没有,py官网已经发话了20200101开始停止支持python2.7,所以人家都不用了吧。

feature1: 类型注解

python3.5的特性。
**存在的必要性:**方便提示变量的函数。现在的IDE做的都贼智能化,可以提示变量能调用的函数,这样的好处很多,防止误拼,加快打字节奏,尤其是工程较大时,记不住所有类函数,这时候联想功能就很amazing了。但python2的特色就是无变量类型。pyhton3.5就重新拾回这一特性了,真香回归现场,哈哈哈。
**不合理性:**失去了模板函数的优势。

举个栗子

实现一个加法函数

# python2.7
def add(a, b):
    return a+b

# python3.7 
def add(a: int, b: int = 0) -> int:
    return a+b

feaure2: dataclass

python3.7的特性。
存在的合理性:减少一遍白痴的赋值,人性化。python2.7的类构造函数一般就是用来赋值的,将外界变量存成类的成员变量(貌似其他语言的构造函数也一样),将函数参数与__init__函数的赋值合二为一,人性化。
不合理性:貌似没有,哈哈哈。

举个栗子

实现一个student类

在这里插入代码片
# python2.7
class student(object):
  """this is an example class"""
  def __init__(self, 
               name,
               id,
               age = 18):
    self.name=name
    self.id=id
    self.age=age

# python3.7
@dataclass
class student:
  """this is a dataclass example"""
  name: str 
  id: int
  age: int = 18

本文地址:https://blog.csdn.net/RogersStar/article/details/107169855

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网