Python类练习及类的使用-自定义with语句

class Player():            
    def __init__(self,name,hp,occu):
        # self.name=name   
        self.__name = name 
        self.hp=hp
        self.occu=occu
    def print_role(self):  
        # print('%s: %s %s' %(self.name,self.hp,self.occu))
        print('%s: %s %s' % (self.__name, self.hp, self.occu))
    def updateName(self,newname):
        self.name=newname



class Monster():
    '定义怪物类'
    def __init__(self,hp=100):
        self.hp = hp
    def run(self):
        print('移动到某个位置')
    def whoami(self):
        print('我是怪物父类')

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

class Boss(Monster):
    'Boss类怪物'
    def __init__(self,hp=1000):
        super().__init__(hp)
    def whoami(self):
        print('我是怪物我怕谁')

a1 = Monster(200)
print(a1.hp)
print(a1.run())
a2 = Animials(1)
print(a2.hp)
print(a2.run())

a3 = Boss(800)
a3.whoami()

print('a1的类型 %s' %type(a1))
print('a2的类型 %s' %type(a2))
print('a3的类型 %s' %type(a3))

print(isinstance(a2,Monster)) 



user1 = Player('tom',100,'war')   
user2 = Player('jerry',80,'master')
user1.print_role()
user2.print_role()

user1.updateName('wilson')
user1.print_role()
user1.name='aaa'
user1.print_role()

自定义with语句

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 runing')
    raise NameError('testNameError')
此条目发表在Python分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Protected with IP Blacklist CloudIP Blacklist Cloud