第36课 类和对象:给大家介绍对象
多态:不同对象对同一方法响应不同的行动
class Person:
name = "小甲鱼"
def printName(self):
print("name is %s" % self.name)
p = Person()
p.printName()
Person.printName(p)
在Python的解释器内部,当我们调用p.printName()时,实际上Python解释成Person.printName(p),也就是说把self替换成类的实例。
把上面的p.printName()一行改写一下,运行后的实际结果完全相同。
name is 小甲鱼
name is 小甲鱼
class Person:
name = "小甲鱼"
def printName():
print("name is %s" % name)
p = Person()
p.printName()
Person.printName(p)
#如果不加self参数的话,显示 printName() takes 0 positional arguments but 1 was given
#定义一个矩形类并生成类实例对象
class Rect:
length = 3
width = 2
def setRect(self):
self.length = float(input("矩形的长为:"))
self.width = float(input("矩形的宽为:"))
def getRect(self):
print("矩形的长为:%.3f 矩形的的宽为:%.3f" % (self.length, self.width))
def getArea(self):
return self.length * self.width
rect = Rect()
rect.getRect()
rect.setRect()
rect.getRect()
print(rect.getArea())
矩形的长为:3.000 矩形的的宽为:2.000
矩形的长为:4
矩形的宽为:6
矩形的长为:4.000 矩形的的宽为:6.000
24.0
第37课 类和对象:面向对象编程
#!/usr/bin/python
# coding:utf-8
#anan
'''
学到的语法:
1.random.randint(0,9) 生成 0 ~ 9 之间的随机数 包含0和9
random.randint(a,b):用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n:a<=n<=b,即[a,b]
# 生成 0 ~ 9 之间的随机数
# 导入 random(随机数) 模块
import random
print(random.randint(0,9))
2.exec函数
for i in range(10):
exec ("temp%s=1"%i)
遗留问题:
1.exec和if如何结合使用
最后代码有一些逻辑问题,主要是因为上面那个问题没有解决,等以后遇到同样的问题再回来解决
已经很棒了,通过这个练习也学到了很多东西
2.对self参数还是一知半解的,不是很懂,希望可以通过后面的练习逐步加强
'''
import random
class Game: #类名要大写
def __init__(self):
self.turtle_weight = 100
self.turtle_count = 1
self.fish_count = 10
self.xmin = 0
self.xmax = 10
self.ymin = 0
self.ymax = 10
self.cycle_number = 100
def fish_move(self, x, y):
direction = random.randint(1,4)
if x == self.xmax:
x -= 1
elif x == self.xmin:
x += 1
elif y == self.ymax:
y -= 1
elif y == self.ymin:
y += 1
elif direction == 1: #往左
x -= 1
elif direction == 2: #往右
x += 1
elif direction == 3: #往上
y += 1
else: #往下
y -= 1
return x, y
def turtle_move(self, x, y, weight):
direction = random.randint(1, 4)
len = random.randint(1, 2)
if x >= self.xmax:
x -= len
elif x <= self.xmin:
x += len
elif y >= self.ymax:
y -= len
elif y <= self.ymin:
y += len
elif direction == 1: #往左
if x == self.xmin+1:
x -= 1
else:
x -= len
elif direction == 2: #往右
if x == self.xmax-1:
x += 1
else:
x += len
elif direction == 3: #往上
if y == self.ymax-1:
y += 1
else:
y += len
elif direction == 4: #往下
if y == self.ymin+1:
y -= 1
else:
y -= len
weight -= 1
return x, y, weight
def game_rule(self):
turtle_x= random.randint(self.xmin, self.xmax)
turtle_y= random.randint(self.ymin, self.ymax)
turtle_weight= self.turtle_weight
print("龟的初始位置及体重:\n%d,%d,%d" %(turtle_x, turtle_y, turtle_weight))
fish_count = self.fish_count
print("鱼的初始位置:")
for i in range(self.fish_count):
x = random.randint(self.xmin, self.xmax)
y = random.randint(self.ymin, self.ymax)
exec("fish_%d_x = %d" %(i, x)) #循环定义赋值
exec("fish_%d_y = %d" %(i, y))
exec("print(fish_%d_x, fish_%d_y)" %(i, i))
print("\n************Game begins**********")
for num in range(self.cycle_number):
#print
if turtle_weight == 0:
print("龟已死!")
break
if fish_count == 0:
print("鱼已死!")
break
for i in range(self.fish_count):
#exec("if turtle_x == fish_%d_x and turtle_y == fish_%d_y" %(i,i)) #这样子不行
# if(exec("(turtle_x == fish_%d_x and turtle_y == fish_%d_y)" %(i,i))): #这样子就行了,哈哈,开心
# print("%%%%%%%%")
# turtle_weight += 20
# fish_count -= 1
# exec("fish_%d_x = -100" % i)
# exec("fish_%d_y = -100" % i)
exec("""if "turtle_x == fish_%d_x and turtle_y == fish_%d_y" %(i,i):
\n print("%%%%%%%%")
\n turtle_weight += 20
\n fish_count -= 1
\n exec("fish_%d_x = -100" % i)
\n exec("fish_%d_y = -100" % i)
\n exec("print(fish_%d_x, fish_%d_y)" % (i, i))""")
# tmp_x = 200
# tmp_y = 200
# exec("tmp_x = fish_%d_x" % i)
# exec("tmp_y = fish_%d_y" % i)
# if turtle_x == tmp_x and turtle_y == tmp_y:
# print("%%%%%%%%")
# turtle_weight += 20
# fish_count -= 1
# exec("fish_%d_x = -100" % i)
# exec("fish_%d_y = -100" % i)
# print("第%d次移动,第%d条鱼的位置:" % (num+1, i+1), end = "")
# if tmp_x < 0 and tmp_y < 0:
# print("第%d条鱼已死!" % (i+1))
# continue
# exec("""if "fish_%d_x < 0 and fish_%d_y < 0" %(i,i):
# \n print("第%d条鱼已死!" % (i+1))
# \n continue""")
exec("(fish_%d_x, fish_%d_y) = self.fish_move(fish_%d_x, fish_%d_y)" % (i, i, i, i))
exec("print(fish_%d_x, fish_%d_y)" % (i, i))
(turtle_x, turtle_y, turtle_weight) = self.turtle_move(turtle_x, turtle_y, turtle_weight)
print("第%d次移动,龟的位置及体重:%d,%d,%d\n" %(num+1, turtle_x, turtle_y, turtle_weight))
print("Game over!")
game = Game()
game.game_rule()
#!/usr/bin/python
# coding:utf-8
'''
学习的思想:
1.将乌龟类和鱼类分开写 自己当时考虑到了这样写,但是后面的游戏规则不太好弄,就放弃了,写到一起了
2.乌龟类的属性写到了__init__函数里面,实现了初始化,值得学习
3.乌龟类的移动规则经自己验证,完美地诠释了所需要求,自己当时写的时候就感觉有点繁琐
4.生成的鱼类对象放到了一个列表中,对这个列表进行循环,每次死掉的鱼就直接移出列表,这样就避免了自己写代码时候的“不知道该怎么处理死掉的鱼”的问题
学习的语法:
1.random.choice函数 choice() 方法返回一个列表,元组或字符串的随机项。
import random
print "choice([1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9])
print "choice('A String') : ", random.choice('A String')
choice([1, 2, 3, 5, 9]) : 2
choice('A String') : n
2.range(start, stop[, step]) 包括start 不包括stop 创建一个整数列表
>>>range(10) # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3.为什么要加这一句
# -*- coding: utf-8 -*-
# coding:utf-8
PY文件当中是不支持中文的,即使你输入的注释是中文也不行,为了解决这个问题,就需要把文件编码类型改为UTF-8的类型,输入这个代码就可以让PY源文件里面有中文了。
建议你写代码之前都把这句话加上,因为不管是注释还是弹出消息提示,免不了的要输入中文,所以这个基本是必须的。
4.关于脚本第一行的 #!/usr/bin/python 的解释,相信很多不熟悉 Linux 系统的同学需要普及这个知识,脚本语言的第一行,只对 Linux/Unix 用户适用,用来指定本脚本用什么解释器来执行。
有这句的,加上执行权限后,可以直接用 ./ 执行,不然会出错,因为找不到 python 解释器。
5.return (self.x, self.y)
自己没有这样返回,自己的是 return x, y,没有加括号,所以后面调用的时候,就不太方便
6.fish是一个列表
fish.append()
fish.remove()
'''
import random as r
legal_x = [0, 10]
legal_y = [0, 10]
class Turtle: #类名要大写
def __init__(self):
self.power = 100
self.x = r.randint(legal_x[0], legal_x[1])
self.y = r.randint(legal_y[0], legal_y[1])
def move(self):
new_x = self.x + r.choice([1, 2, -1, -2])
new_y = self.y + r.choice([1, 2, -1, -2])
if new_x < legal_x[0]:
self.x = legal_x[0] - (new_x - legal_x[0])
elif new_x > legal_x[1]:
self.x = legal_x[1] - (new_x - legal_x[1])
else:
self.x = new_x
if new_y < legal_y[0]:
self.y = legal_y[0] - (new_y - legal_y[0])
elif new_y > legal_y[1]:
self.y = legal_y[1] - (new_y - legal_y[1])
else:
self.y = new_y
self.power -= 1
return (self.x, self.y)
def eat(self):
self.power += 20
if self.power > 100:
self.power = 100
class Fish:
def __init__(self):
self.x = r.randint(legal_x[0], legal_x[1])
self.y = r.randint(legal_y[0], legal_y[1])
def move(self):
new_x = self.x + r.choice([1, -1])
new_y = self.y + r.choice([1, -1])
if new_x < legal_x[0]:
self.x = legal_x[0] - (new_x - legal_x[0])
elif new_x > legal_x[1]:
self.x = legal_x[1] - (new_x - legal_x[1])
else:
self.x = new_x
if new_y < legal_y[0]:
self.y = legal_y[0] - (new_y - legal_y[0])
elif new_y > legal_y[1]:
self.y = legal_y[1] - (new_y - legal_y[1])
else:
self.y = new_y
return (self.x, self.y)
turtle = Turtle()
fish = []
for i in range(10):
new_fish = Fish()
fish.append(new_fish)
while True:
if not len(fish):
print('鱼儿都死掉啦!Game over!')
break
if not turtle.power:
print("乌龟已死!Game over!")
break
pos_turtle = turtle.move()
print("\n乌龟位置为:", end="")
print(pos_turtle)
for each_fish in fish[:]: #平时用的range也是生成一个列表
pos_fish = each_fish.move()
print("鱼的位置为:", end="")
print(pos_fish)
if pos_fish == pos_turtle:
turtle.eat()
fish.remove(each_fish)
print("一条鱼被吃掉了")
第38课 类和对象:继承
#!/usr/bin/python
# -*- codinig: utf-8 -*-
class Myclass:
def __init__(self):
return "I love 养乐多!"
test = Myclass()
#TypeError: __init__() should return None, not 'str'
#!/usr/bin/python
# -*- codinig: utf-8 -*-
'''
学到的知识点:
1.求平方
1)使用内置模块
>>> import math
>>> math.pow(12, 2) # 求平方
144.0
>>> math.sqrt(144) # 求平方根
12.0
2)使用表达式
>>> 12 ** 2 # 求平方
144
>>> 144 ** 0.5 # 求平方根
12.0
3)使用内置方法
>>> pow(12, 2) # 求平方
144
>>> pow(144, .5) # 求平方根
12.0
'''
import math
class Point:
def __init__(self):
self.x = float(input("请输入点的横坐标:"))
self.y = float(input("请输入点的纵坐标:"))
class Line(Point):
def __init__(self):
self.point1 = Point()
self.point2 = Point()
def getLen(self):
self.length = math.sqrt((self.point1.x-self.point2.x)**2 + (self.point1.y-self.point2.y)**2)
return self.length
line = Line()
print(line.getLen())
第39课 类和对象:拾遗
#!/usr/bin/python
# -*- coding: utf-8 -*-
#自己的顾虑:没有办法初始化呀
# class An:
# def __init__(self):
# self.count = 0
'''
学到的语法:
1.创建对象后,Python解释器默认调用__init__()方法。
当删除一个对象时,Python解释器也会默认调用一个方法,这个方法为__del__()方法。
在Python中,对于开发者来说很少会直接销毁对象(如果需要,应该使用del关键字销毁)。
Python的内存管理机制能够很好的胜任这份工作。
也就是说,不管是手动调用del还是由Python自动回收都会触发__del__方法执行。
'''
#小甲鱼
#把初始化的count当成了一个属性
class C:
count = 0
def __init__(self):
C.count += 1
def __del__(self):
C.count -= 1
a = C()
b = C()
c = C()
print(C.count)
del a
print(C.count)
del b, c
print(C.count)
#!/usr/bin/python
# -*- codinig: utf-8 -*-
class Stack:
def __init__(self, dataList):
self.dataList = dataList
self.length = len(self.dataList)
self.topp = self.length - 1
def isEmpty(self):
if self.topp < 0:
return True
else:
return False
def push(self, data):
self.dataList.append(data)
self.length += 1
self.topp += 1
def pop(self):
#del.self.dataList[self.top]
#self.dataList.remove()
self.length -= 1
self.topp -= 1
return self.dataList.pop(self.topp+1)
def top(self):
return self.dataList[self.topp]
def bottom(self):
return self.dataList[0]
stack = Stack([1, 2, 3, 4, 5])
print(stack.pop())
print(stack.top())
print(stack.bottom())
stack.push(6)
print(stack.length)