类和对象
class Hero(object):
def info(self):
print("英雄不问出处")
print(self)
nova = Hero()
nova.info()
nova.name = "新星"
nova.hp = 2000
nova.atk = 500
nova.armor = 200
print("英雄:%s\n生命值:%s\n攻击力:%s \n防御力:%s\n"%(nova.name, nova.hp, nova.atk, nova.armor))
class Hero (object):
def move(self):
print("赶往战场")
def attack(self):
print("攻击")
def info(self):
print("英雄:%s\n生命值:%s\n攻击力:%s \n防御力:%s\n" % (self.name, self.hp, self.atk, self.armor))
nova = Hero()
nova.name = "新星"
nova.hp = 2000
nova.atk = 500
nova.armor = 200
nova.info()
nova.move()
nova.attack()
输出:
英雄:新星
生命值:2000
攻击力:500
防御力:200
赶往战场
攻击 注意self的用法
魔法方法
__init__
def __init__(self,参数1,...,参数n):
self.属性1 = 参数1
......
self.属性n = 参数n
__str__
def __str__(self):
msg = "嘿...我的颜色是" + self.color + ",我有%d"%self.wheelNum+ "个轮胎..."
return msg
__del__
def __del__(self):
pass
多态
class F1(object):
def show(self):
print("F1SHOW")
class S1(F1):
def show(self):
print("S1SHOW")
class S2(F1):
def show(self):
print("S2SHOW")
def Func(obj):
print(obj.show())
s1_obj = S1()
Func(s1_obj)
s2_obj = S2()
Func(s2_obj)
类方法:@classmethod
静态方法:@staticmethod
class PEOPLE(object):
country = "CHINA NB"
@staticmethod
def getcountry():
return PEOPLE.country
p = PEOPLE()
p.getcountry()
print(PEOPLE.getcountry())
异常:
try:
a = open(LLL.txt)
prin
except Exception as res:
print("find error")
print(res)
print("---"*10)
输出: find error
name 'LLL' is not defined
------------------------------
res只能在函数里面用,拿出来报错