深度学习基础系列之一:Python语言特性总结

205 阅读3分钟

python语言特性

本篇适合有JS编程基础的小伙伴阅读,如果没有编程基础的,建议先去看《python编程 从入门到实践》或戳廖雪峰老师的python教程

特性

  • List的基本api

    List就是Python的Array,其中往list增加元素可以使用append,insert;删除可以使用pop,delete以及remove。

  • 元组

    可以把元组看成不可变的list,适合存储一些“常量”的列表。但是注意可以直接改变原变量的引用地址:

    myFav = ('cake', 'coke', 'sugar')
    myFav[0] = 'vagetable' # no no no
    myFav = ('vagetable', 'rice', 'fish') # work
    
  • 切片

    切片是python特好用的一个特性,可以很方便的截取List(相当于Array)且不改变原List,仍然是取头不取尾,对数据的处理特别有用。

    message = ['John', 'Dean', 'Sami', 'Josh']
    message[:]  # ['John', 'Dean', 'Sami', 'Josh']
    message[1:2] # ['Dean']
    message[1:-1] # ['Dean', 'Sami']
    
  • 字典

    把这个理解成Json对象就可以了。注意有几个属性方法items(), keys(), values()害挺有用

  • 循环

    Python的循环写起来非常简便

    user_0 = {
    
      'username': 'efermi',
    
      'first': 'enrico',
    
      'last': 'fermi',
    
    }
    
    for key, value in user_0.items():
    
        print("\nKey: " + key)
    
        print("Value: " + value)
    

    和其他语言基本一致,稍微提一嘴。

  • 类与继承

    Python中的类有几个特殊的点

    1. 使用class ClassName(): 定义,其中class的c不需要大写,后接(): 而不是{};
    2. constructor在这里是def __ init __(self, *args):,其中self是必要的形参;
    3. 实例化一个类的时候,不需要使用关键字new,直接 ClassName(arg)即可
    class Dog():
    
        """一次模拟小狗的简单尝试"""
    
        def __init__(self, name, age):
    
            """初始化属性name和age"""
    
            self.name = name
    
            self.age = age
    
        def sit(self):
    
            """模拟小狗被命令时蹲下"""
    
            print(self.name.title() + " is now sitting.")
    
        def roll_over(self):
    
            """模拟小狗被命令时打滚"""
    
            print(self.name.title() + " rolled over!")
            
            
    # 实例化
    my_dog = Dog('willie', 6)
    

    继承的实现也很有趣,直接在类定义的括号里传递父类,并在构造函数里面super父类的构造函数即可:

     class SmallDog(Dog):
         def __init__():
             super().__init__(args) # 这里传递父类构造函数__init__的需要参数
    

    这样就实现了类的继承,现在只要实例化一个子类,就可以直接调用父类的方法了。

  • 模块

    Python的模块不需要刻意导出,只需要在导入时声明就可以了:

    from dog import SmallDog 
    from dog import Dog
    from dog import * 
    import dog
    
  • 文件

    python里面会经常处理数据文件,因此文件api也非常重要。

    # 打开文件并读取
    with open('pi_digits.txt') as file_object:
        contents = file_object.read()
        print(contents)
        
    # 打开文件逐行读取
    filename = 'pi_digits.txt'
    with open(filename) as file_object:
        for line in file_object:
            print(line)
    
    #覆盖写入
    filename = 'programming.txt'
    with open(filename, 'w') as file_object:
        file_object.write("I love programming.")
        file_object.write("I love creating new games.")
    
    # 追加写入
    filename = 'programming.txt'
    with open(filename, 'a') as file_object:
        file_object.write("I also love finding meaning in large datasets.\n")
        file_object.write("I love creating apps that can run in a browser.\n")
    
    
  • 错误处理

    在Python中的错误处理稍稍有些特别,也单独提出来说一说,python使用的是catch except else的格式:

      print("Give me two numbers, and I'll divide them.")
      print("Enter 'q' to quit.")
      while True:
          first_number = input("\nFirst number: ")
          if first_number == 'q':
              break
          second_number = input("Second number: ")
          try:
              answer = int(first_number) / int(second_number)
          except ZeroDivisionError:
              print("You can't divide by 0!")
          else:
              print(answer)
    

持续优化