python类

class Role(object):
ac = None;
count = 0
def __init__(self,name, role, weapon, life_value):
self.name = name;
self.role = role;
self.weapon = weapon;
self.life_value = life_value;
Role.count += 1

def buy_weapon(self,weapon):
print ("%s is buying [%s]" %(self.name, weapon))
self.weapon = weapon


p1 = Role("zhangsan", 'Police', "B10", 100)
t1 = Role("lisi", 'Terrorist', "B11", 90)

p1.buy_weapon("AK47")
t1.buy_weapon("B51")

print("p1:" , p1.weapon)
print("t1:" , t1.weapon)

p1.ac = "China"
t1.ac = "USA"
print(p1.ac)
print(t1.ac)

p1.count = 3; 在p1 中创建一个 count 变量

print(Role.count) 类中的count 变量
print(p1.count)
print(t1.count) 实例中如果没有创建同名的类变量,则访问的是 类变量。

  输出:

zhangsan is buying [AK47]
lisi is buying [B51]
p1: AK47
t1: B51
China
USA
2
3
2

class Role(object):   括号中的是继承的父类。
 def __init__(self,name, role, weapon, life_value): 是构造方法。
p1 = Role("zhangsan", 'Police', "B10", 100) 实例化。 相当于 Role(p1,"zhangsan", 'Police', "B10", 100 )
p1.buy_weapon("AK47")   相当于 Role.buy_weapon(p1,"AK47")     self 代表实例本身。
posted @ 2017-08-27 00:54  zhoudingzhao  阅读(106)  评论(0编辑  收藏  举报