标签:bin doc def __name__ 属性 col %s python面向对 python
由面向对象的思想引入面向对象的设计,最后面向对象编程。
#!/usr/bin/env python # coding:utf-8 def school(name,addr,type): def init(name, addr, type): sch = { ‘name‘: name, ‘addr‘: addr, ‘type‘: type, ‘kao_shi‘: kao_shi, ‘zhao_sheng‘: zhao_sheng, } return sch def kao_shi(school): print(‘%s 学校正在考试‘ %school[‘name‘]) def zhao_sheng(school): print(‘%s %s 正在招生‘ %(school[‘type‘],school[‘name‘])) return init(name,addr,type) print("面向对象的设计") s1=school(‘oldboy‘,‘沙河‘,‘私立学校‘) print(s1) print(s1[‘name‘]) s1[‘zhao_sheng‘](s1) s2=school(‘清华‘,‘北京‘,‘公立学校‘) print(s2) print(s2[‘name‘],s2[‘addr‘],s2[‘type‘]) s2[‘zhao_sheng‘](s2)
类的练习:
#!/usr/bin/env python # coding:utf-8 ## 类:把一类事物的相同的特征和动作整合到一起就是类,类是一个抽象的概念 ## 对象:就是基于类而创建的一个具体的事物(具体存在的)也是特征和动作整合到一起 # class Chinese: # 经典类 python2中的区分 # ‘‘‘这是一个中国人的类‘‘‘ # pass # # print(Chinese) # # # class Chinese(object): # 新式类 python2中的区分 # pass # 实例化到底干了什么? # p1 = Chinese() # 实例化 并不像其它语言使用new # print(p1) ## python3中不再区分,都是新式类 class Chinese: ‘‘‘这里写文档注释‘‘‘ # 1 数据属性 area = "Asia" # 2 函数属性 def dun(): print("亚洲蹲") def speak(self): print("讲汉语 %s" % self) print(dir(Chinese)) print(Chinese.__dict__) # 查看类的属性字典,字典里存放着类的数据属性和函数属性 print(Chinese.area) Chinese.dun() Chinese.__dict__[‘dun‘]() Chinese.__dict__[‘speak‘]("你好") print(Chinese.__name__) # 类名 print(Chinese.__doc__) # 类的文档注释 print(Chinese.__base__) # 基类 <class ‘object‘> print(Chinese.__bases__) # 基类 (<class ‘object‘>) print(Chinese.__module__) # 来自模块
类的练习二:
#!/usr/bin/env python # coding:utf-8 class Chinese: ‘‘‘这里写文档注释‘‘‘ area = "Asia" # def init(name,age,gender): # dic={ # ‘name‘:name, # ‘age‘:age, # ‘gender‘:gender # } # return dic def __init__(self, name, age, gender): print("start...") self.aname = name self.aage = age self.agender = gender print("end...") ## 自动return None 所以,不能加return def dun(self): print("%s 亚洲蹲在 %s " % (self.aname,self.area)) def speak(self,lang): print("%s 讲%s " % (self.aname, lang)) p1 = Chinese("Tom",22,"male") # 实例化 print(p1.__dict__) print(p1.aname) print(p1.agender) print(p1.area) p1.dun() p1.speak(‘本地方言‘) print(p1.area) # 修改 Chinese.area = ‘东方大陆‘ # 修改函数 def xia_dun(self): print("%s 坐在了地上。" % self.aname) Chinese.dun = xia_dun # 修改了类的内部函数 # 增加 Chinese.skin = ‘yellow‘ p2 = Chinese("小明",11,"男") print(p2.area) print(p2.skin) print(p1.skin) # 之前的实例也可以用,因为实例是对类的引用 p2.dun() # 删除 # del Chinese.area # print(p2.area)
老师http://www.cnblogs.com/linhaifeng/articles/6182264.html
标签:bin doc def __name__ 属性 col %s python面向对 python
原文地址:https://www.cnblogs.com/frx9527/p/python_ood.html