【代码】传智播客 Python基础班+就业班

工厂方法模式:基类定义接口,子类具体实现

class Store(object):

	#此处选车并不会执行
	def select_car(self):
		print("Store:select_car")
		
	# 店铺只负责订购功能,添加选车接口
	def order(self, car_type):
		return self.select_car(car_type)

class BMW_Car_Store(Store):
	#继承基类,实现自己的选车方案,即调用工厂类
	def select_car(self, car_type):
		return BMW_Factory().select_car_by_type(car_type)		

class BMW_Factory(object):
	#被调用类的最终选车实现
	def select_car_by_type(self, car_type):
		print("BMW_Factory in BMW_Car_Store")

bmw_store = BMW_Car_Store()
bmw = bmw_store.order("720li")

tcp server

from socket import *
#创建服务器套接字,绑定ip端口,监听(被动连接)数量
svr_skt = socket(AF_INET, SOCK_STREAM)
svr_skt.bind(('',7789))
svr_skt.listen(4)

#创建服务器接收到待客户端(阻塞,等客户端连入),及其ip和port
clt_skt, clt_info = svr_skt.accept()

#接收数据
recv_data = clt_skt.recv(1024)
print str(clt_info)+':'+str(recv_data)

#发送数据,将字符串中文编码
#svr_skt.send('hello xp'.encode('gb2312'))
#此处send数据报错:socket.error: [Errno 32] Broken pipe

#关闭客户端,再服务器
clt_skt.close()
svr_skt.close()

tcp client

from socket import *
#创建套接字,绑定服务器端口
clt_skt = socket(AF_INET, SOCK_STREAM)
clt_skt.connect(('192.168.37.3',8989))
#连接后即发送信息,此处c发给s成功,而s发给c失败
clt_skt.send('hello xp'.encode('gb2312'))
#接收数据
rcv_data = clt_skt.recv(1024)
print(rcv_data)
#关闭套接字
clt_skt.close()

udp receive & send

from socket import *
#创建套接字,绑定接收ip和端口
udp_skt = socket(AF_INET, SOCK_DGRAM)
bind_addr = ('',7788)
udp_skt.bind(bind_addr)
#输入待发送信息,发送
send_info = raw_input('input infomation to send:')
udp_skt.sendto(str(send_info),('192.168.37.3',8080))
#等待接收信息,
recv_data = udp_skt.recvfrom(1024)
print str(recv_data[1])+':'+recv_data[0]
#关闭套接字
udp_skt.close()

创建单例对象

class Dog(object):

	#实例创建次数标识,初始化传参标识
	__instance = None
	__init_flag = False
	
	# 只初始化一次对象
	def __init__(self, name):
		if Dog.__init_flag == False:
			self.name = name
			Dog.__init_flag = True

	def __new__(cls, name):
		# 创建单例对象
		if cls.__instance == None:
			cls.__instance = object.__new__(cls)
			return cls.__instance
		else:
			return cls.__instance
			
# 创建第一个
q = Dog("q")
print(q.name)
print(id(q))

# 创建第二个
r = Dog("r")
print(id(q), id(r))
print(q.name, r.name)

老王开枪

# ========gunner shoot=========
class Person(object):
	"""docstring for Person"""
	def __init__(self, name):
		super(Person, self).__init__()
		self.name = name
		self.gun = None 	# storage cite of gun object 存储枪对象引用
		self.power = 100

	def setup_bullet(self, clip, bullet):
		# setup clip with bullets
		clip.save_bullet(bullet)

	def setup_clip(self, gun, clip):
		#setup gun with clip
		gun.save_clip(clip)

	def pick_gun(self, gun):
		#pick up gun
		self.gun = gun

	def shoot(self, target):
		# with gun
		self.gun.fire(target)
		
	def hurted(self, kill_ability):
		self.power -= kill_ability

	def __str__(self):
		# if one has gun, return his power 
		if self.gun:
			return "{0}\'s power is {1}, {2}".format(self.name, self.power, self.gun)
		else:
			if self.power > 0:
				return 	"{0}\'s power is {1}, no gun".format(self.name, self.power)
			else:
				return 	"{0}\'s killed".format(self.name)


class Gun(object):
	"""docstring for Gun"""
	def __init__(self, name):
		super(Gun, self).__init__()
		self.name = name
		self.clip = None
	def save_clip(self, clip):
		self.clip = clip

	def fire(self, target):
		# bullet out from clip 子弹出弹夹
		bullet = self.clip.popup()
		# if has bullet, then hit target 如果弹夹非空,射击敌人
		if bullet:
			bullet.hit(target)
		else:
			print("no bullet")

	def __str__(self):
		if self.clip:
			return "gun info: {0}, {1}".format(self.name, self.clip)
		else:
			return "gun info: {0}, no clip".format(self.name)



class Clip(object):
	"""docstring for Clip"""
	def __init__(self, max_num):
		super(Clip, self).__init__()
		self.max_num = max_num	# max num of clip 弹夹最大容量
		self.bullet_list = []	# storage cite of bullet object 存储子弹对象的引用

	def save_bullet(self, bullet):
		# push bullet into clip # 将子弹压入弹夹
		self.bullet_list.append(bullet)

	def popup(self):
		# clip popup upest bullet, if no bullet, return None  弹夹弹出子弹
		if self.bullet_list:
			return self.bullet_list.pop()
		else:
			return None

	def __str__(self):
		return "clip info: {0}/{1}".format(len(self.bullet_list), self.max_num)


class Bullet(object):
	"""docstring for Bullet"""
	def __init__(self, kill):
		super(Bullet, self).__init__()
		# kill ability 杀伤力
		self.kill = kill
	def hit(self, target):
		# target lose life power value: kill 敌人失去生命力值: 杀伤力
		target.hurted(self.kill)
		
		
def main():
	# 1.gunner 枪手
	gunner = Person("gunner")

	# 2.gun 枪
	ak47 = Gun("ak47")

	# 3.clip 弹夹
	clip = Clip(20)

	# 4.create some bullets 创建一些子弹
	# 	setup clip with these bullets 将这些子弹装入弹夹
	for i in range(10):
		# bullet with kill_ability 子弹,带杀伤力
		bullet = Bullet(10)

		# setup_bullet  装子弹
		gunner.setup_bullet(clip, bullet)

	# 4.setup_clip 装弹夹
	gunner.setup_clip(ak47, clip)

	# 5.pick_gun 拿枪
	gunner.pick_gun(ak47)

	# test clip info 测试信息
	# print(clip)
	# test gun info
	# print(ak47)
	# test gunner object
	print(gunner)	

	# 6.target 敌人
	target = Person("target")
	print(target)

	# 7.shoot_target in 12 times 射击12次
	for i in range(12):
		gunner.shoot(target)
		print(target)
		print(gunner, end="\n\n")

if __name__ == '__main__':
	main()

猜你喜欢

转载自blog.csdn.net/C_Python_/article/details/83239094