python 问题

class Role(object):
n = 123 # 类变量
n_list = []
k = "我是类变量"
k_list = []
def __init__(self, name, role, weapon, life_value=100, money=15000):
# __init__:
# 构造函数
# 在实例化时作一些类的初始化的工作

self.name = name # 变量赋给了实例,为实例变量(静态属性),作用域就是实例本身
self.role = role
self.weapon = weapon
self.life_value = life_value
self.money = money

def shot(self): # 类的方法(功能)(动态属性)
print("shooting...")

def got_shot(self):
print("ah...,I got shot...")

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


r1 = Role('Alex', 'police', 'AK47') #实例化 --> 对象(也成为类的实例) 生成一个角色
r2 = Role('Jack', 'terrorist', 'B22') #生成一个角色

print("-------------")
print(Role.k_list)
print(r1.k_list)
print(r2.k_list)
print("-------------")
r2.k_list.append("aa1")
print(r1.k_list)
print(r2.k_list)
print(Role.k_list)

1.为什么修改列表后能够把类变量的列表也修改了?
posted @ 2019-12-17 19:41  树下的猫  阅读(74)  评论(0)    收藏  举报