添加和获取对象的属性
class Hero(object):
"""定义了一个英雄类,可以移动和攻击"""
def move(self):
"""实例方法"""
print("正在前往事发地点...")
def attack(self):
"""实例方法"""
print("发出了一招强力的普通攻击...")
taidamier = Hero()
taidamier.name = "泰达米尔"
taidamier.hp = 2600
taidamier.atk = 450
taidamier.armor = 200
print("英雄 %s 的生命值 :%d" % (taidamier.name, taidamier.hp))
print("英雄 %s 的攻击力 :%d" % (taidamier.name, taidamier.atk))
print("英雄 %s 的护甲值 :%d" % (taidamier.name, taidamier.armor))
taidamier.move()
taidamier.attack()
在方法内通过self获取对象属性
class Hero(object):
"""定义了一个英雄类,可以移动和攻击"""
def move(self):
"""实例方法"""
print("正在前往事发地点...")
def attack(self):
"""实例方法"""
print("发出了一招强力的普通攻击...")
def info(self):
"""在类的实例方法中,通过self获取该对象的属性"""
print("英雄 %s 的生命值 :%d" % (self.name, self.hp))
print("英雄 %s 的攻击力 :%d" % (self.name, self.atk))
print("英雄 %s 的护甲值 :%d" % (self.name, self.armor))
taidamier = Hero()
taidamier.name = "泰达米尔"
taidamier.hp = 2600
taidamier.atk = 450
taidamier.armor = 200
taidamier.info()
taidamier.move()
taidamier.attack()