在群里下载XX Python培训机构的PDF,里面有一段小游戏代码;本着菜鸟,努力码代码的心态。结果运行时报错,提示:


#!/usr/bin/env python
# coding=utf-8


class unit:
    def __init__(self):
        self.___blood_max =  self.___blood
        print self.name + " created"

        
class attacker(unit):
    def attack(self,u):
        u.__blood -= self.dps
        if u.__blood <= 0:
            print u.name + " was dead!!!"
            del u
        else:
            print u.name + " was attacked !  __blood = " + str(u.__blood)


class machineGun(attacker):
    def __init__(self,name):
        self.__blood = 100
        self.name = name
        unit.__init__(self)
        self.dps = 30
        print self.name + " Created"
        

class tree(unit):
    def __init__(self,name):
        self.name = name
        print self.name + " Created"
        
class healer(unit):
    def __init__(self,name):
        self.__blood = 50
        self.name = name
        unit.__init__(self)
        self.hps = 15
        print self.name + " Created"
        
    def heal(self,u):
        u.__blood += self.hps
        if u.__blood >= u.__blood_max:
            u.__blood = u.__blood_max
        print u.name + "was healed ! __blood = " +  str(u.__blood)
        

j1 = machineGun("j1")
j2 = machineGun("j2")
h1 = healer("h1")

j1.attack(j2)
j1.attack(j2)
h1.heal(j2)
j1.attack(j2)
j1.attack(j2)
j1.attack(j2)

    

错误如下:

Traceback (most recent call last):
  File "C:\Users\Cranezhou\workspace\test\test01\game.py", line 50, in
    j1 = machineGun("j1")
  File "C:\Users\Cranezhou\workspace\test\test01\game.py", line 25, in __init__
    unit.__init__(self)
  File "C:\Users\Cranezhou\workspace\test\test01\game.py", line 7, in __init__
    self.___blood_max =  self.___blood
AttributeError: machineGun instance has no attribute '_unit___blood'


    后经在XX培训群,咨询大神;说__开头的变量,在Python后来的版本中定义有变动。替换为一个下划分线后,程序总算可以运行了。


    后经再次查看eclipe debug,想起__开头的变量是私有变量;父类构建函数中字段,赋值等于子类中属性时,找不到相对应的属性,实属正常。


    后续:测试,子类 能不能引用 父类中的私有变量?