Python-100 days from novice to master - learning notes

Keywords: Python github

Write at the front

For various reasons, Xi mentioned the longest winter vacation in history.
I have nothing to do at home. At the same time, because the project needs to use Python related content (in fact, it's keras, there's no ready-made code, so I'm going to start learning python.
This series is notes. Please move to Miss Luo Hao's GitHub for details.
Python - 100 days from novice to master

Object oriented correlation

It's probably better to remember this part with an example of Altman fighting small monsters.

Ultraman fighting the little monster

There is an Altman and several small monsters. Altman can use normal attack, or consume MP to use magic attack, or consume a lot of MP to use big moves. Among them, magic attack is AOE damage, common attack and big move are single damage. The small monster that receives single damage will fight back.

from abc import ABCMeta, abstractmethod
from random import randint, randrange

class Fighter(object, metaclass=ABCMeta):
    '''Combatants'''
    #The restriction can only add two attributes, namely "name" and "HP". It is only valid for the Fighter class
    #For properties that are recommended to be private (immutable), they usually start with
    __slots__ = ('_name', '_hp')

    def __init__(self, name, hp):
        self._name = name
        self._hp = hp

    @property
    def name(self):
        return self._name
    #Accessor, only accessible, not modifiable

    @property
    def hp(self):
        return self._hp

    @hp.setter
    def hp(self, hp):
        self._hp = hp if hp >= 0 else 0
    #Modifiers, allow modification

    @property
    def alive(self):
        return self._hp > 0

    @abstractmethod
    def attack(self, other):
        ''':param other:  Attacker'''
        pass
    #Static method, tangible without reality

class Ultrman(Fighter):
    '''Ultraman'''
#Subclass of Fighter class, inherited
    __slots__ = ('_name', '_hp', '_mp')

    def __init__(self, name, hp, mp):
        super().__init__(name, hp)#Initialization, available in parent class
        self._mp = mp

    def attack(self, other):
        '''Common attack'''
        other.hp -= randint(10, 15)

    def magic_attack(self, others):
        '''
        //20MP at a time, AoE damage
        mp If not enough, the attack fails
        '''
        if self._mp >= 20:
            self._mp -= 20
            for temp in others:
                if temp.alive:
                    temp.hp -= randint(10, 30)
            return True
        else:
            print('------mp Insufficient, turn to normal attack-------\n')
            return False

    def huge_attack(self, other):
        '''
        //Big move, 3 / 4 HP or at least 50
        //Blue loss 50
        '''
        if self._mp >= 50:
            injure = other.hp / 4 * 3
            other.hp -= 50 if 50 > injure else injure
            return True
        else:
            print('------mp Insufficient, turn to normal attack-------\n')
            return False

    def resum(self):
        '''
        //Recover [1, 10] mp at random for each general attack
        '''
        increase = randint(1, 10)
        self._mp += increase
        return increase

    def __str__(self):#display information
        return '\n%s:\n' % self.name + \
               'Life value: %d ' % self.hp + \
               'Magic value: %d' % self._mp

class Monster(Fighter):

    __slots__ = ('_name', '_hp')

    def attack(self, other):
        other.hp -= randint(5, 30)

    def __str__(self):
        return '%s:\n' % self.name + \
               'Life value: %d' % self.hp

def is_any_alive(monsters):
    for monster in monsters:
        if monster.alive:
            return True
    return False

def select_monster(monsters):
    number_monster = len(monsters)
    while True:
        index = randint(0, number_monster - 1)
        if monsters[index].alive:
            return monsters[index]

def display_info(ultraman, monsters):#Display information under str method
    print(ultraman)
    for monster in monsters:
        print(monster, end='\n')

def main():
    u = Ultrman('The masses of the people', 1000, 1000)
    m1 = Monster('Hubei Red 10', 10000)
    m2 = Monster('Governor of Hubei', 10000)
    m3 = Monster('Mayor of Wuhan', 10000)
    ms = [m1, m2, m3]
    fight_round = 0
    while u.alive and is_any_alive(ms):
        fight_round += 1
        print('\n=======The first%d round========' % fight_round)
        m = select_monster(ms)
        i = randint(1, 10)
        if i <= 6:
             u.attack(m)
             print('%s Using normal attack %s' % (u.name, m.name))
             print('%s Restore Magic: %d' % (u.name, u.resum()))
        elif i <= 9:
            if u.magic_attack(ms):
                print('%s Attack with magic' % u.name)
            else:
                u.attack(m)
                print('%s Using normal attack %s' % (u.name, m.name))
                print('%s Restore Magic: %d' % (u.name, u.resum()))
        else:
             if u.huge_attack(m):
                print('%s Used a trick' % u.name)
             else:
                u.attack(m)
                print('%s Using normal attack %s' % (u.name, m.name))
                print('%s Restore Magic: %d' % (u.name, u.resum()))
        if m.alive:
            m.attack(u)
            print('%s Hit back. %s' % (m.name, u.name))
        display_info(u, ms)
    print('====End of battle====')
    if u.alive:
        print('%s Win victory' % u.name)
    else:
        print('This netizen can't')

if __name__ == '__main__':
    main()

On static methods

Similar to static methods, Python can also define class methods in a class. The first parameter convention of class methods is named cls, which represents the object related to the current class (the class itself is also an object, sometimes referred to as the metadata object of the class). Through this parameter, we can obtain class related information and create class objects and codes As shown below.

from time import time, localtime, sleep

class Clock(object):
    """Digital clock"""

    def __init__(self, hour=0, minute=0, second=0):
        self._hour = hour
        self._minute = minute
        self._second = second

    @classmethod
    def now(cls):
        ctime = localtime(time())
        return cls(ctime.tm_hour, ctime.tm_min, ctime.tm_sec)

    def run(self):
        """be in luck"""
        self._second += 1
        if self._second == 60:
            self._second = 0
            self._minute += 1
            if self._minute == 60:
                self._minute = 0
                self._hour += 1
                if self._hour == 24:
                    self._hour = 0

    def show(self):
        """Display time"""
        return '%02d:%02d:%02d' % \
               (self._hour, self._minute, self._second)

def main():
    # Create objects and get system time through class methods
    clock = Clock.now()
    while True:
        print(clock.show())
        sleep(1)
        clock.run()

if __name__ == '__main__':
    main()
Published 5 original articles, praised 0, visited 812
Private letter follow

Posted by rokkstar on Sat, 01 Feb 2020 23:20:32 -0800