Python进阶-XIV 面向对象初步
1、面向对象的引入
1 def Person(*args): 2 ''' 3 定义一个人 4 :param args: 人的属性 5 :return: 人的所有属性的字典 6 ''' 7 info = {} 8 info['name'] = args[0] 9 info['age'] = args[1] 10 info['hp'] = args[2] 11 info['aggr'] = args[3] 12 13 def fight(info, dog): 14 ''' 15 人打 16 :param person:一个具体的人 17 :param dog: 一只具体的狗 18 :return: 19 ''' 20 dog[ 'hp' ] -= info[ 'aggr' ] 21 22 return info,fight 23 24 def Dog(*args): 25 ''' 26 定义一个狗 27 :param args: 狗的属性 28 :return: 狗的所有属性的字典 29 ''' 30 info = {} 31 info[ 'name' ] = args[ 0 ] 32 info[ 'hp' ] = args[ 1 ] 33 info[ 'aggr' ] = args[ 2 ] 34 35 def bite(info, person): 36 ''' 37 狗咬 38 :param dog: 哪只狗 39 :param person: 哪个人 40 :return: 41 ''' 42 person[ 'hp' ] -= info[ 'aggr' ] 43 return info,bite 44 45 # 代码精简了 方便增加人物 方便修改 人物更加规范 —— 人模子 46 47 p_tupl = Person('tom',18, 500, 100) 48 49 d_tupl = Dog('wancai',300, 150) 50 51 # todo 如果将bite和fight放在此处,人狗的行为可能混乱@ 52 # print('被咬前:', tom) 53 # bite(wancai, tom) 54 # print('被咬后:',tom) 55 # 56 # print('被打前:', wancai) 57 # fight(tom, wancai) 58 # print('被打后:',wancai) 59 # 60 # # 人也可以咬狗,不合理!于是将咬的方法放入Dog函数中!打的方法也一样! 61 # #bite(tom, wancai) 62 63 tom = p_tupl[0] 64 wancai = d_tupl[0] 65 66 print('被咬前:', tom) 67 d_tupl[1](wancai, tom) 68 print('被咬后:',tom) 69 70 print('被打前:', wancai) 71 p_tupl[1](tom, wancai) 72 print('被打后:',wancai) 73 74 # 面向对象编程 75 # 所谓模子 就是 类 抽象的 我能知道有什么属性 有什么技能 但不能知道属性具体的值 76 # jin alex nezha 就是对象 有具体的值,属性和技能都是根据类规范的
2、初识面向对象
1 # 用对象模拟人狗大战 2 3 ''' 4 人类 5 ''' 6 class Person: # 类名 7 coutry = 'PRC' # 创造了一个只要是这个类就一定有的属性 8 # 类属性 静态属性 9 def __init__(self, *args): # 初始化方法,self是对象,是一个必须传的参数 10 self.name = args[0] # self就是一个可以存储很多属性的大字典 11 self.age = args[1] # 往字典里添加属性的方式发生了一些变化 12 self.hp = args[2] 13 self.aggr = args[3] 14 15 def fight(self, dog): # 方法,一般情况下必须传self参数,且必须写在第一个 16 ''' # 后面还可以传其他参数,是自由的 17 人打 18 :param person:一个具体的人 19 :param dog: 一只具体的狗 20 :return: 21 ''' 22 dog.hp -= self.aggr 23 24 ''' 25 狗类 26 ''' 27 class Dog: 28 def __init__(self, *args): 29 self.name = args[ 0 ] 30 self.hp = args[ 1 ] 31 self.aggr = args[ 2 ] 32 33 def bite(self, person): 34 ''' 35 狗咬 36 :param dog: 哪只狗 37 :param person: 哪个人 38 :return: 39 ''' 40 person.hp -= self.aggr 41 42 tom = Person('tom',18, 500, 100) # 类名还可以实例化对象,alex对象 # 实例化 43 print(tom.coutry) # 类名 可以查看类中的属性,不需要实例化就可以查看 44 wancai = Dog('wancai',300, 150) 45 46 print(tom.age, tom.hp) # 查看属性值 47 48 print('被咬前:', tom.__dict__) # 查看所有属性 49 wancai.bite( tom) # 调用方法 类名.方法名(对象名) 50 print('被咬后:',tom.__dict__) 51 # 52 print('被打前:', wancai.__dict__) 53 tom.fight(wancai) 54 print('被打后:',wancai.__dict__) 55 56 # 对象 = 类名() 57 # 过程: 58 # 类名() 首先 会创造出一个对象,创建了一个self变量 59 # 调用init方法,类名括号里的参数会被这里接收 60 # 执行init方法 61 # 返回self 62 # 对象能做的事: 63 # 查看属性 64 # 调用方法 65 # __dict__ 对于对象的增删改查操作都可以通过字典的语法进行 66 # 类名能做的事: 67 # 实例化 68 # 调用方法 : 只不过要自己传递self参数 69 # 调用类中的属性,也就是调用静态属性 70 # __dict__ 对于类中的名字只能看 不能操作

浙公网安备 33010602011771号