《零基础学Python》--第2章 面向对象编程

174 阅读1分钟

类的实例、属性、方法和继承

方法后面第一个参数一定是self super().init()父类初始化属性后,子类不需要重复初始化,直接调用该方法

class Player:      #定义一个类
    def __init__(self,name,hp):
        self.__name = name    #变量被称作属性,属性前面加双下划线表示不可被直接调用
        self.hp = hp
    def print_role(self):   #定义一个方法
        print('%s的血量为%s' %(self.__name,self.hp))

user1 = Player('sun',100) #类的实例化
user1.print_role

class Monster:
    '定义怪物类'
    def __init__(self, hp=100): #参数后面带值为默认值
        self.hp = hp
    def run(self):
        print('移动到某个位置')
    def who_am_i(self):
        print('我是怪物父类')

class Animals(Monster):
    '普通怪物'
    def __init__(self, hp=10):
        super().__init__(hp)

class Boss(Monster):
    'Boss类怪物'
    def __init__(self, hp=1000):
        super().__init__(hp)
    def who_am_i(self):     #和父类重名的方法会覆盖
        print('我是Boss')


自定义with语句

  • 自定义with语句时需要实现两个方法
    • enter(self)
    • exit(self, exc_type, exc_val, exc_tb)
class TestWith:
    def __enter__(self):    
        print('run')
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_tb is None:
            print('正常结束')
        else:
            print('has error %s' % exc_tb)

with TestWith():
    print('test is running')
    raise NameError('test nameError')

作为程序执行

  • 该结构表示如果当前文件用python运行,中间的语句就会执行,如果当做模块导入,语句就不会执行
if __name__ == '__main__':
    #语句