面向对象的编程
类的定义:
class 类名(父类名)
调用类:
类名()
<对其进行实例化对象的过程>
***封装特性***
#定义一个水果类 class Fruit(object): #构造函数<实例化对象时自动调用的函数> def __init__(self,name,color,price): #把对象和属性进行绑定 self.name=name self.color=color self.price=price #在类里构造的函数称为方法 def eat(self): print('%s味道是甜的'%self.name) a=Fruit('apple','red','5yuan') print(a.price) print(a.name) print(a.color) a.eat()
***继承特性***
#定义一个水果类 class Fruit(object): def __init__(self,name,color,price): self.name=name self.color=color self.price=price def eat(self): print('%s味道是甜的'%self.name) #定义另一个便宜的水果类 class Cheapfruit(Fruit): def __init__(self,name,color,price,count): #对父类属性的继承 super(Cheapfruit, self).__init__(name,color,price) self.count=count a=Cheapfruit('apple','red','5yuan',5) print(a.color) print(a.count) a.eat()#子类没有的函数,子动调用父类的函数,子类有的函数优先调用子类的函数
类的多继承:
>新式类(python3)
在某一类存在多个父类的情况下:采用广度优先的原则进行函数的调用
>经典类(python2)
采用深度优先的原则
类的私有属性:
只有该类对该属性有访问和修改的权限
***类的基础练习***
游戏规则:
1. 游戏背景为10*10;
2. 游戏会自动生成1个乌龟和10条鱼;
3. 它们移动方向随机;
4. 乌龟最大移动能力为2; [-2,-1,1,2]
5. 鱼最大移动能力为1; [-1,1]
6. 当移动到场景边界, 自动反方向移动;
7. 乌龟初始化体能为100<200为上限>;每移动一次消耗体能1;
8. 当乌龟和鱼的坐标重合, 代表乌龟吃掉鱼, 体能增加20;
9. 乌龟无体力或者鱼吃光, 游戏结束;
import random class Base(object): def __init__(self): self.x = random.randint(0, 9) self.y = random.randint(0, 9) def is_vaild(self, point): if point < 0: return 0 - point elif point > 9: return 9 - (point - 9) return point class Turtle(Base): def __init__(self): super(Turtle, self).__init__() self.power = 100 def move(self): move_skill = [-1, 1, 0, -2, 2] new_x = self.x + random.choice(move_skill) new_y = self.y + random.choice(move_skill) self.x = self.is_vaild(new_x) self.y = self.is_vaild(new_y) self.power -= 1 def eat(self): self.power += 20 if self.power >= 200: self.power = 200 class Fish(Base): def move(self): move_skill = [0, 1, -1] new_x = self.x + random.choice(move_skill) new_y = self.y + random.choice(move_skill) self.x = self.is_vaild(new_x) self.y = self.is_vaild(new_y) def main(): T = Turtle() F = [Fish() for i in range(10)] while 1: if T.power == 0: print('乌龟累死了!Game Over!') break elif F == []: print('鱼被吃光了!Game Over!') break else: T.move() for fish in F: fish.move() if fish.x == T.x and fish.y == T.y: T.eat() F.remove(fish) print('一条鱼被吃掉!') print('乌龟剩余体力:%s' % T.power) if __name__ == '__main__': main()
魔术方法
***构造函数,析构函数,__str__***
class house(object): #__init__是在实例化对象开始时自动调用的函数 def __init__(self,high,width,length): self.high=high self.width=width self.length=length #__str__是在实例化对象时调用的函数 def __str__(self): return '高:{d.high} 宽:{d.width} 长:{d.length}'.format(d=self) #__del__是在调用结束时调用的函数 def __del__(self): print( '谢谢使用...') print(house('3米','5米','20米'))
***__format__魔术方法对对象的属性进行自定义处理***
info={ 'MNA':'早上:{d.morning}--中午:{d.noon}--下午:{d.afternoon}', 'ANM':'下午:{d.afternoon}\n中午:{d.noon}\n早上:{d.morning}' } class schedule(object): def __init__(self,morning,noon,afternoon): self.morning=morning self.noon=noon self.afternoon=afternoon def __format__(self, format_spec): if not format_spec: format_spec='MNA' return info[format_spec].format(d=self) a=schedule('看电视','踢球','学习') print(format(a,'ANM')) print(format(a))
***__getitem__,__setitem__,__delitem__***
让实例化对象具有字典的key:value特性或者索引切片特性
eg:
class student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = score def __getitem__(self, item): #self.__dict__对象的属性为key值 属性的值为value值 return self.__dict__[item] def __setitem__(self, key, value): self.__dict__[key] = value def __delitem__(self, key): del self.__dict__[key] a=student('张龙','20',(100,90,80,70)) print(a['name']) print(a['score']) a['gender']='男' print(a['gender']) del a['score'] print(a.score)
***__itrer__赋予对象可迭代的特性__gt__大小比较魔术__eq__相等魔术@functools.total_ordering模块***
import functools @functools.total_ordering class student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = score def __iter__(self): return iter(self.score) def __gt__(self, other): sum1 = sum(self.score) sum2 = sum(other.score) return sum1 > sum2 def __eq__(self, other): sum1 = sum(self.score) sum2 = sum(other.score) return sum1 == sum2 a = student('小明', '19', (67, 54, 86, 94)) b=student('小华','20',(78,34,98,76)) for i in a: print(i) print(a>b) print(a<=b)
***@property模块将方法变成属性****
class book(object): def __init__(self, name, author, state): self.name = name self.author = author self.__state = state def __str__(self): return 'hello {b.name} hello {b.author}'.format(b=self) @property def state(self): if self.__state == 1: return '借出' else: return '未借出' @state.setter def state(self, value): if value in [0, 1]: self.__state = value else: print('状态只能是0或者1') B = book('python', 'guido', 1) print(B) print(B.state) #修改属性 B.state = 0 print(B.state)
***类方法和静态方法***
class Date(object): def __init__(self, year, month, day): self.year = year self.month = month self.day = day def echo(self): print("Year:%s\nMonth:%s\nDay:%s" % (self.year, self.month, self.day)) @classmethod #类方法:实例化之前对对象进行处理,返回的是一个处理后的实例化对象 def str_date(cls, s): year, month, day = map(int, s.split('-')) d = cls(year, month, day) return d #静态方法:独立于整个类 @staticmethod def is_date_legal(s): year, month, day = map(int, s.split('-')) return year > 0 and 0 < month <= 12 and 0 < day <= 31 d = Date.str_date('2018-1-4') d.echo() print ("合法") if Date.is_date_legal("2018-1-4") else "不合法"
***.format字符串个格式化***
# 通过位置来传参数 print('hello {}'.format('python')) print('hello {0} hello {1} hello {2} {1}'.format(1, 2, 3, 4)) print('hello {0:.2f} hello {1:.3f} hello {2:.2f} {1:.2f}'.format(1.423, 2.5435, 3.52542, 4)) # 通过key值来传参数 print('hello {max} hello {min}'.format(max='python', min='java')) # 通过下标来传参数 print('hello {0[2]} {1[0]}'.format([1, 2, 4], (4, 5, 6))) # 打印对象时子动调用 class book(object): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return 'hello {b.name} hello {b.age}'.format(b=self) print(book('wang', '20'))
附录:
***END***