廖雪峰Python学习笔记day5

一时失言乱红尘 2022-12-23 09:46 255阅读 0赞

学习笔记day4

  1. # python study day5
  2. # 匿名函数 lambda 参数列表: 返回值表达式
  3. # f = lambda x, y: x*y
  4. # print(f(2,3)) #>>> 6
  5. # 装饰器 decorator,不修改原函数定义,动态增加功能的方式
  6. # def log(func): # 对函数添加打印日志
  7. # def wrapper(*args, **kw): # 匹配任何函数参数形式
  8. # print('call %s():' % func.__name__) # __name__函数属性:获取函数名
  9. # return func(*args, **kw)
  10. # return wrapper
  11. # import time
  12. # @log
  13. # def now():
  14. # print(time.strftime('%Y-%m-%d', time.localtime()))
  15. # now() #>>> call now(): 2020-11-23
  16. # log(now)() #>>>
  17. # call wrapper():
  18. # call now():
  19. # 2020-11-23
  20. # 带参数decorator:
  21. # import functools,time
  22. # def log(text):
  23. # def decorator(func):
  24. # @functools.wraps(func) # 相当于wrapper.__name__=func.__name__
  25. # def wrapper(*args, **kw):
  26. # print('%s %s():' % (text, func.__name__))
  27. # return func(*args, **kw)
  28. # return wrapper
  29. # return decorator
  30. # @log('execute')
  31. # def now():
  32. # print(time.strftime('%Y-%m-%d', time.localtime()))
  33. # now() #>>>
  34. # execute now():
  35. # 2020-11-23
  36. # 打印函数执行时间
  37. # import time, functools
  38. # def metric(fn):
  39. # now = time.time()
  40. # @functools.wraps(fn) # 缺少该项将影响原函数名
  41. # def wrapper(*args, **kw):
  42. # result = fn(*args, **kw)
  43. # print('%s executed in %s ms' % (fn.__name__, time.time()-now))
  44. # return result
  45. # return wrapper
  46. # @metric
  47. # def test(x, y):
  48. # time.sleep(1.005)
  49. # return x*y
  50. # print(test(3,4)) #>>>
  51. # test executed in 1.0050718784332275 ms
  52. # 12
  53. # 偏函数,将原有函数参数固定默认值创建新函数
  54. # int('123', base=8) # 八进制转换,简写 int('123', 8) >>> 83
  55. # def int2(x, base=2): # 该函数默认二进制转换,int()是十进制
  56. # return int(x, base)
  57. # 使用 functools.partial 创建偏函数
  58. # import functools
  59. # int2 = functools.partial(int, base=2)
  60. # print(int2('1010101')) #>>> 85
  61. # 添加固定参数绑定函数
  62. # max2 = functools.partial(max, 10)
  63. # print(max2(5, 6, 7)) #>>> 10
  64. # 模块,一个.py文件就是一个模块,模块之间可以相互调用
  65. # 为避免模块名冲突,引入包,如 mypackage.abc.func
  66. # 每个包下必须有一个__init__.py的文件(可以为空,也可以有代码)
  67. # 标准模块使用
  68. # #!/usr/bin/env/python3 #(可以让该文件直接在Unix/Linux/Mac上运行)
  69. # # -*- coding: utf-8 -*- #(当前文件使用标准utf-8编码)
  70. # 'a test module' # 模块第一个字符串为文档注释
  71. # __author__ = 'your name' # 添加模块作者信息
  72. # /*编写代码*/
  73. # import sys # 引入sys文件
  74. # args = sys.argv # 使用argv模块变量
  75. # 运行python3 hello.py 获得 sys.argv 就是 ['hello.py']
  76. # 运行python3 hello.py Michael 获得 sys.argv 就是 ['hello.py', 'Michael']
  77. # 作用域,public(公开)、private(私有) (python没有做限制,建议约定俗成)
  78. # 特殊变量:__author__、__name__、__doc__……
  79. # _xxx、__xxx、_xxx_ 如_abc、_func_等定义为private不应该直接被引用
  80. # def _private_1(name):
  81. # return 'Hello, %s' % name
  82. # def _private_2(name):
  83. # return 'Hi, %s' % name
  84. # def greeting(name):
  85. # if len(name) > 3:
  86. # return _private_1(name)
  87. # else:
  88. # return _private_2(name)
  89. # 安装第三方模块,通过包管理工具pip完成
  90. # 如安装图像类库 Pillow, 通过windows上命令提示符窗口运行 pip3 install Pillow
  91. # 如果安装速度慢、超时,可以考虑修改为国内镜像数据源
  92. # 如果需要安装模块比较多,可以统一安装Anaconda,内置有许多常用模块
  93. # OOP 面向对象编程,程序的基本单元是对象
  94. # 面向过程编程是函数集合的顺序执行,推荐使用OOP
  95. # class Student(object): # 定义学生类对象,object 继承的父类
  96. # def __init__(self, name, score): # 构造方法,初始化对象,self表示实例本身
  97. # self.__name = name
  98. # self.__score = score # 对象私有属性
  99. # def get_name(self):
  100. # return self.__name
  101. # def set_name(self, name):
  102. # self.__name = name
  103. # def get_score(self):
  104. # return self.__score
  105. # def set_score(self, score):
  106. # self.__score = score
  107. # def print_score(self): # 对象公有方法
  108. # print('%s: %s' % (self.__name, self.__score))
  109. # stu1 = Student('Lily', 99) # 实例化对象
  110. # stu1.print_score() # 调用实例方法
  111. # stu1.__name # 直接访问私有属性不可
  112. # 对__xxx__此类是特殊变量,不是私有属性定义,so不能用__name__命名
  113. # 继承和多态,子承父类,子类可调用/重写父类方法
  114. # class Animal(object):
  115. # def run(self):
  116. # print('Animal is running...')
  117. # class Dog(Animal):
  118. # pass
  119. # class Cat(Animal):
  120. # def run(self):
  121. # print('cat is running...')
  122. # dog = Dog()
  123. # cat = Cat()
  124. # dog.run() #>>> Animal is running...
  125. # cat.run() #>>> cat is running...
  126. # def run_twice(animal): # 对 animal 参数不一定是Animal对象实例,只要有run()即可
  127. # animal.run()
  128. # run_twice(Dog()) #>>> Animal is running...
  129. # run_twice(Cat()) #>>> cat is running...
  130. # dog、cat = Cat() 也是一个类型,相当于 a = list(),
  131. # 可以使用isinstance(cat, Animal)判断 #>>> True
  132. # 动态语言 python 是鸭子类型(file-like object),不像静态语言(如java)强类型限制
  133. # 获取对象类型,type()、isinstance() 推荐使用isinstance()(可判断子父类继承)
  134. # type('abc') == str #>>> True
  135. # import types
  136. # type(fn) == types.FunctionType #>>> True
  137. # type(abs) == types.BuiltinFunctionType #>>> True
  138. # type(lambda x: x) == types.LambdaType #>>> True
  139. # type((x for x in range(10)))) == types.GeneratorType #>>> True
  140. # isinstance(dog, Dog) and isinstance(dog, Animal) #>>> True
  141. # isinstance((1,3), (list, tuple)) # 多类型判断 >>> True
  142. # 获取对象所有属性和方法 dir()
  143. # print(dir('abc')) #>>>
  144. # ['__add__', '__class__', '__contains__', '__delattr__',
  145. # '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
  146. # '__getattribute__', '__getitem__', '__getnewargs__',
  147. # '__gt__', '__hash__', '__init__', '__init_subclass__',
  148. # '__iter__', '__le__', '__len__', '__lt__', '__mod__',
  149. # '__mul__', '__ne__', '__new__', '__reduce__',
  150. # '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
  151. # '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
  152. # 'capitalize', 'casefold', 'center', 'count', 'encode',
  153. # 'endswith', 'expandtabs', 'find', 'format', 'format_map',
  154. # 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal',
  155. # 'isdigit', 'isidentifier', 'islower', 'isnumeric',
  156. # 'isprintable', 'isspace', 'istitle', 'isupper', 'join',
  157. # 'ljust', 'lower', 'lstrip', 'maketrans', 'partition',
  158. # 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
  159. # 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
  160. # 'swapcase', 'title', 'translate', 'upper', 'zfill']
  161. # len('abc') # 等价于 'abc'.__len__()
  162. # hasattr(object, 'x') # 判断对象object是否有属性或方法‘x’
  163. # setattr(object, 'y', 1) # 设置属性‘y’
  164. # getattr(object, 'y') # 获取属性‘y’
  165. # getattr(object, 'y', 404) # 获取失败返回404

在这里插入图片描述
学习笔记day6

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读