Python随心记--函数之面向对象
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python随心记--函数之面向对象相关的知识,希望对你有一定的参考价值。
函数之面向对象
def dog(name,type): def jiao(dog): ret = ‘一只%s再叫,哈哈哈‘ % dog[‘name‘] return ret def chi(dog): ret = ‘一只%s在吃饭,吃吃吃‘ % dog[‘type‘] return ret def init(name,type): dog = { ‘name‘:name, ‘type‘:type, ‘jiao‘:jiao, ‘chi‘:chi, } return dog return init(name,type) d1 = dog(‘小白兔‘,‘哈士奇‘) d2 = dog(‘小黑兔‘,‘阿拉斯加‘) print(d1[‘jiao‘](d1)) print(d1[‘chi‘](d1)) print(d1[‘jiao‘](d2)) print(d1[‘chi‘](d2))
#面向对象:
类:
动作跟特征的结合(共同的特征,共同的动作)
把一类事物的相同的特征和动作整合到一起
是一个抽象的概念
对象:就是居于类而创建的一个具体的事物
#用面向对象语言写程序和一个程序的设计是面向对象编程
#新式类(python2中)
class School(object): def __init__(self,name,type): self.name = name self.type = type def bark(self): return ‘%s在招生‘ %self.name d = School(‘清华‘,‘公立‘) #实例化对象 print(d.bark())
#经典类 (__init__里面不能return值)
class School: #声明一个类 def __init__(self,name,type): self.name = name self.type = type def bark(self): return ‘%s在招生‘ %self.name d = School(‘清华‘,‘公立‘) #实例化对象 print(d.bark())
class Chinese: ‘这是一个中国类‘ nationality = ‘中国‘ #属性 ancestralhome = ‘广东‘ #属性 def __init__(self,name,age,gender): self.name = name self.age = age self.gender = gender def common(self): return ‘%s人不吃辣‘ %self.name def commons(self): return ‘%s人喜欢吃辣‘ %self print(Chinese.__name__) #打印类名 print(Chinese.__doc__) #打印文档 print(Chinese.__base__) print(Chinese.__bases__) print(Chinese.__module__) #模块 print(Chinese.__class__) chainese = Chinese() print(Chinese.nationality) #访问属性 print(Chinese.ancestralhome) #访问属性 print(Chinese.common(chainese)) #访问方法 print(dir(Chinese)) print(Chinese.__dict__) #查看类的属性字典 print(Chinese.__dict__[‘nationality‘]) #打印类的属性 print(Chinese.__dict__[‘ancestralhome‘]) #打印类的属性 print(Chinese.__dict__[‘commons‘]()) #执行类的方法 chainese = Chinese(‘广东‘,‘13‘,‘中国‘) print(chainese.__dict__) print(chainese.common())
class Chinese: ‘这是一个中国类‘ nationality = ‘中国‘ #属性 ancestralhome = ‘广东‘ #属性 def __init__(self,name,age,gender): self.name = name self.age = age self.gender = gender def common(self): return ‘%s人不吃辣‘ %self.name def eatfood(self,food): return ‘%s人喜欢喝%s‘ %(self.name,food) chainese = Chinese(‘广东‘,‘13‘,‘中国‘) print(chainese.common()) print(chainese.eatfood(‘早茶‘)) Chinese.ancestralhome = ‘深圳‘ #修改属性 chainese.addr = ‘广州‘ #增加属性 del Chinese.ancestralhome #删除属性 def eat_food(self,food): return ‘%s人喜欢喝%s‘ % (self.name, food) Chinese.eat = eat_food #增加方法 把eat_food方法增加到Chinese类中 Chinese.common = eat_food #修改 把common方法修改为eat_food # print(chainese.__dict__) print(chainese.eat(‘茶‘))
county = ‘北京‘ class Chinese: ‘这是一个中国类‘ nationality = ‘中国‘ #属性 ancestralhome = ‘广东‘ #属性 def __init__(self,name,age,gender): #print(county) #能打印北京,这里跟普通变量没什么差别,如果用self.county就会报错 self.name = name self.age = age self.gender = gender def common(self): return ‘%s人不吃辣‘ %self.name def eatfood(self,food): return ‘%s人喜欢喝%s‘ %(self.name,food) chainese = Chinese(‘广东‘,‘13‘,‘中国‘)
面向对象之静态属性
class Room: tag = 1 #静态属性 def __init__(self,name,length,width,hiegh): self.Name = name self.Length = length self.Width = width self.Hiegh = hiegh @property #加上装饰器 def cal_area(self): return self.Width * self.Length def test(self): print(‘from test‘,self.Name) def tall_info(self): print(‘--->‘,self.tag) @classmethod # 加上只会tall_info就会变成专门给类使用的方法 def tall_info1(cls): print(cls) print(‘--->‘, cls.tag) print(‘--->‘, Room.tag) @classmethod # 加上只会tall_info就会变成专门给类使用的方法 def tall_info2(cls,x): print(cls) print(‘--->‘, cls.tag, x) room = Room(‘卧室‘,100,100,100) print(room.cal_area()) #加上装饰器@property之前调用 print(room.cal_area) #加上装饰器@property之后调用 print(Room.tag) #调用属性 Room.test(room) Room.tall_info(room) 加上装饰器@classmethod之前调用 Room.tall_info1() #加上装饰器@classmethod之后调用 Room.tall_info2(10) #加上装饰器@classmethod之后调用
#静态方法
class Room: tag = 1 #静态属性 def __init__(self,name,length,width,hiegh): self.Name = name self.Length = length self.Width = width self.Hiegh = hiegh @property #加上装饰器 def cal_area(self): return self.Width * self.Length def test(self): print(‘from test‘,self.Name) def tall_info(self): print(‘--->‘,self.tag) @classmethod # 加上只会tall_info就会变成专门给类使用的方法 def tall_info1(cls): print(cls) print(‘--->‘, cls.tag) print(‘--->‘, Room.tag) @classmethod # 加上只会tall_info就会变成专门给类使用的方法 def tall_info2(cls,x): print(cls) print(‘--->‘, cls.tag, x) @staticmethod #类的工具包 不能调用类变量和实例变量 def wash_boyd(): #可以传参数也可以不传参数 print(‘正在洗澡‘) room = Room(‘卧室‘,100,100,100) Room.wash_boyd() room.wash_boyd()
组合
class Hand: pass class Foot: pass class Head: pass class Trunk: pass class Person: def __init__(self,id_num,name): self.id_num = id_num self.name = name self.hand = Hand() self.food = Foot() self.trunk = Trunk() self.head = Head()
组合(查询学校信息)
#学校类 class School: def __init__(self,name,addr): self.name = name self.addr = addr #课程类 class Course: def __init__(self,name,price,perioc,school): self.name = name self.price = price self.perioc = perioc self.school = school schoolo = School(‘老男孩‘,‘北京‘) schoolt = School(‘传 智‘,‘天津‘) schoolh = School(‘泰 牛‘,‘上海‘) # print(c1.__dict__) msg = ‘‘‘ 1 老男孩北京校区 2 老男孩天津校区 3 老男孩上海校区 ‘‘‘ while True: print(msg) menu = { ‘1‘ : schoolo, ‘2‘ : schoolt, ‘3‘ : schoolh, } choice = input(‘请选择您想要了解的校区序号>>>:‘) course = Course(‘liunx‘, ‘10000‘, ‘6‘, menu[choice]) # 把学校类传给课程类 print(‘课程属于【%s】,地址在【%s】‘ %(course.school.name,course.school.addr)) # 拿到oldboy
#继承、多态、封装
继承
#面向对象之继承 class ParentClass: money = 100 def __init__(self,name): self.name = name def hit_son(self): return ‘%s 正在运行‘ %self.name class ParentClasss: pass class SubClass(ParentClass): #单继承 pass class SubClasss(ParentClass,ParentClasss): #多继承 pass sub = SubClass(‘函数‘) # print(sub.money) print(‘子类调用父类的hit_son函数‘,sub.hit_son())
接口继承:
子类必须实现父类的所有方法
import abc #接口模块 class AllFile(metaclass=abc.ABCMeta): @abc.abstractmethod def read(self): pass @abc.abstractmethod def write(self): pass class Disk(AllFile): def read(self): print(‘Disk rand‘) def write(self): print(‘Disk write‘) class Cdrom(AllFile): def read(self): print(‘Cdrom rand‘) def write(self): print(‘Cdrom write‘) class Mem(AllFile): def read(self): print(‘Mem rand‘) def write(self): print(‘Mem write‘)
#接口继承顺序之mro线性(python3)
class D: pass class E: pass class F(D,E): pass print(F.__mro__)
#在子类中调用父类的方法
class Vehicle: Country = ‘China‘ def __init__(self,name,speed,load,power): self.name = name self.speed = speed self.load = load self.power = power def run(self): return ‘【父类】开动啦............‘ class Subway(Vehicle): def __init__(self,name,speed,load,power): super().__init__(name,speed,load,power) # super(Subway,self).__init__(name,speed,load,power) # Vehicle.__init__(self,name,speed,load,power) def show_info(self): return self.name,self.speed def run(self): super().run() # Vehicle.run(self) return ‘%s线开动了‘ %(self.name),super().run() lin13 = Subway(‘深圳13号线‘,‘10km/h‘,1000,‘电‘) print(lin13.show_info()) print(lin13.run())
实例
import uuid import pickle import hashlib import time def creat_md5(): m = hashlib.md5() m.update(str(time.time()).encode(‘utf8‘)) return m.hexdigest() # id = creat_md5() class Base: def save(self): #把实例对象永久化保存(文件方式) with open(‘school.db‘,‘wb‘) as f: pickle.dump(self,f) class School(Base): def __init__(self,name,addr): self.id = creat_md5() self.name = name self.addr = addr #课程类 class Course(Base): def __init__(self,name,price,perioc,school): self.id = creat_md5() self.name = name self.price = price self.perioc = perioc self.school = school school = School(‘老男孩‘,‘沙河‘) school.save() school_obj = pickle.load(open(‘school.db‘,‘rb‘)) #读出保存的对象 print(school_obj)
#面向对象之多态
class H2o: def __init__(self,name,temperature): self.name = name self.temperature = temperature def turn_ice(self): if self.temperature < 0: return ‘【%s】温度太低结冰了‘ %self.name elif self.temperature > 100: return ‘【%s】温度太高变成蒸汽了‘ % self.name else: return ‘【%s】液化成水了‘ % self.name class Water(H2o): pass class Ice(H2o): pass class Steem(H2o): pass water = Water(‘水‘,10) ice = Ice(‘冰‘,-20) steem = Steem(‘蒸汽‘,123) print(water.turn_ice()) print(ice.turn_ice()) print(steem.turn_ice())
#面向对象之封装:
脑子不好使的先别封,没想全面的别封,不然最后你会疯
1 改变 2 扩展
明确内外可否调用,内部能用外部不能用
多态就是类的这两层意义的一个具体的实现机制,即调用不同的类实例化的对象下的相同方法,实现的过程不一样,python中的标准类型就是多态概念的一个很好的示范
真正意义的封装不是停留在封装的层面上
class People: stars = ‘earth‘ _star = ‘earth‘ #被隐藏的属性 类之外不应该被调用,能调用 __star = ‘earth‘ #被隐藏的属性(类似私有的) 类之外不能被调用 如非要调用可如: peoplo._People__star 原因是pythonn会重命名 __width = 23 __lenfth = 24 def __init__(self,id,name,age,salary): self.id = id self.name = name self.age = age self.salary = salary def _get_id(self): print(‘这是我的私有方法,我找到的id是[%s]‘ %self.id) def teststar(): print(self.__star) #外部人可调用该函数求面积 def tell_area(): return self.__width * self.__lenfth peoplo = People(‘232333233‘,‘linm‘,‘13‘,1000000) peoplo._get_id() print(peoplo.__star) peoplo.teststar()
以上是关于Python随心记--函数之面向对象的主要内容,如果未能解决你的问题,请参考以下文章