python之类(class)的笔记

# __*__ coding: utf-8 __*__
# __author__ = "David.z"

# dict ={
#     1:{"name":"alex",
#        "role":"terrorist",
#        "weapon":"C33",
#        "life_value":"100",
#        "money":15000,},
#     1:{"name":"alex",
#        "role":"terrorist",
#        "weapon":"C33",
#        "life_value":"100",
#        "money":15000,},
#     2:{"name":"tom",
#        "role":"terrorist",
#        "weapon":"B25",
#        "life_value":"100",
#        "money":15000,},
#     3:{"name":"jack",
#        "role":"police",
#        "weapon":"B51",
#        "life_value":"100",
#        "money":15000,},
#     4:{"name":"lily",
#        "role":"police",
#        "weapon":"G31",
#        "life_value":"100",
#        "money":15000,},
# }
# print(dict[1])
# print(dict[2])
# print(dict[3])
# print(dict[4])
class Role(object):
    n=123
    n_list=[]

    def __init__(self,name,role,weapon,life_value=100,money=15000):
        #构造函数
        #在实例化时做一些类的初始化的工作
        self.name = name
        self.role = role
        self.weapon = weapon
        self.__life_value = life_value#这个是一个私有属性,如果要调用,需要在里面在加一个方法调用,如def show_status()
        
        self.money = money
    def __del__(self):
        pass
        #print("%s彻底死了。。。"%self.name)
    def show_status(self): #这里就是我在调用私有属性,同理,如果要用私有方法,也是加__
        print("name:%s weapon:%s life_value:%s"%(self.name,
                                                     self.weapon,
                                                     self.__life_value
                                                 ))
        return "hello"
    def shot(self):
        print("%s shooting..."%self.name)

    def got_shot(self):
        print("ah...,%s got shot..."%self.name)

    def buy_gun(self,gun_name):
        print("%s just bought %s"%(self.name,gun_name))

r1 = Role('Alex',"police",'AK47') #实例化,(初始化一个类,造了一个对象)
r1.n="r1变量改了"
r1.n_list.append("r1添加")

r2 = Role('Jack',"terrorist",'B22') #生成一个角色
r2.n="r2变量改了"
Role.n = "类变量改了"
r2.n_list.append("r2添加")
print(r1.show_status())
# print(Role.n,r1.got_shot(),r1.n)
# print("类:",Role.n_list)
# print("r1:",r1.n_list)
# print("r2:",r2.n_list)
# print(Role.n,r2.buy_gun("狙击"),r2.n)

今天开始学习面向对象和面向过程的两种编程方式。

其实我们之前开始写的脚本类的编程,都可以叫做面向对象的编程。

那么什么面向对象,借用Alex的话,世间万物都有是有类可以分的。这里我们就引出了类。

面向对象包括:对象、封装、继承、多态的特性。

类里面我们说有对象和实例化。还包括构造函数和析构函数。

构造函数: def __init__(self):

析构函数: def __del__(self):

猜你喜欢

转载自www.cnblogs.com/davidz/p/9851005.html