python里用类构建CS游戏里的角色

学习知识点:

构造函数

析构函数

私有方法,私有属性

类变量

实例变量

 1 # __*__ coding: utf-8 __*__
 2 __author__ = "David.z"
 3 
 4 class Role:
 5     n = 123 #类变量
 6     n_list=[]
 7     name = "我是类name"
 8     def __init__(self,name,role,weapon,life_value=100,money=15000):
 9         #构造函数
10         #在实例化时做一些类的初始化工作
11 
12         self.name = name #r1.name=name实例变量(静态属性),作用域就是实例本身
13         self.role = role
14         self.weapon = weapon
15         self.__life_value = life_value
16         self.money = money
17     def __del__(self): #析构函数
18         print("%s彻底死了。。。"%self.name)
19     def show_status(self):
20         print("name:%s weapon:%s life_value:%s" %(self.name,self.weapon,self.__life_value))
21     def shot(self):
22         print("shooting...")
23     def got_shot(self):
24         self.__life_value -= 50
25         print("%s:ah...,I got shot..."% self.name)
26 
27     def buy_gun(self,gun_name):
28         print("%s just bought %s"%(self.name,gun_name))
29 r1 = Role('Chenronghua','police','AK47')
30 r1.buy_gun("AK47")
31 r1.got_shot()
32 
33 print(r1.show_status())
34 
35 r2 = Role('jack','terrorist','B22')
36 r2.got_shot()
原文地址:https://www.cnblogs.com/davidz/p/8676305.html