1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# 面向对象 object:表示该类是从哪个类继承下来的 class Student(object): class_name = '类属性,实例和类都能访问' __slots__ = ('name', 'age') # 定义允许绑定的属性名称,只对当前类有效,对子类无效 def __init__(self, name, score): self.__name = name # 加上两个__就变成私有变量了 注意:__变量名__是特殊变量,这样取名不会变成私有变量 self.score = score def print_info(self): print('%s: %s' % (self.__name, self.score)) tang = Student('tang', 100) tang.age = 666 tang.print_info() print(tang.class_name) print(Student.class_name) print(tang.age) print(isinstance(tang, Student)) #True print(isinstance(tang, object)) #True print(type(tang) == Student) #True print(type(tang) == object) #False dir(tang) #获得一个对象的所有属性和方法 hasattr(tang, 'score') #True hasattr(tang, 'print_info') #True setattr(tang, 'score', 66) getattr(tang, 'score') # 给对象动态绑定方法 def set_age(self, age): self.age = age from types import MethodType tang.set_age = MethodType(set_age, tang) # 给类动态绑定方法 Student.set_age = set_age # 类装饰器 class Student(object): @property def score(self): return self.__score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self.__score = value test = Student() test.score = 100 print(test.score) # 多继承 # 通常,主线都是单一继承下来的,需要混入额外的功能,可以使用多继承 # 这种设计通常称之为MixIn(约定俗成) class Bird(Anmial, FlyableMixIn) # 定制类 # __str__、__repr__、__iter__、__next__、__getitem__、__call__等 # 枚举类 from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value) # 枚举类 from enum import Enum, unique @unique class Weekday(Enum): Sun = 7 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 for name, member in Weekday.__members__.items(): print(name, '=>', member, "星期", member.value) # 元类:metaclass 从type类型派生 通常用不到 不展开 # 异常处理 # https://docs.python.org/3/library/exceptions.html#exception-hierarchy def test(num): try: 10 / num print('ok') except Exception as e: print('not ok') finally: print('over') test(1) test(0) # 断言 -O参数能关闭断言 python -O test.py def foo(s): n = int(s) assert n != 0, 'n is zero!' return 10 / n def main(): foo('0') main() # 日志 debug info warning error import logging logging.basicConfig(level=logging.INFO) s = '0' n = int(s) logging.info('n = %d' % n) print(10 / n) # pdb python3 -m pdb test.py # l 查看代码 # n 单步执行 # p 变量名 查看变量 # q 结束调试 # c 继续运行 s = '0' n = int(s) print(10 / n) # 手动设置断点 import pdb s = '0' n = int(s) pdb.set_trace() # 运行到这里会自动暂停 print(10 / n) |