4 python module instances

exp_1

class Person(object):
    '''people'''
    
    def __init__(self, name, age):
        self._name = name
        self._age = age
        
    @property
    def name(self):
        return self._name
    
    @property
    def age(self):
        return self._age
    
    @age.setter
    def age(self, age):
        self._age = age
        
    def play(self):
        print('%s Playing happily.' % self._name)
        
    def watch_av(self):
        if self._age >= 18:
            print('%s Watching love action movies.' % self._name)
        else:
            print('%s Only watch<Bear touch>.' % self._name)

class Student(Person):
    '''Student'''
    
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self._grade = grade
        
    @property
    def grade(self):
        return self._grade

    @grade.setter
    def grade(self, grade):
        self._grade = grade

    def study(self, course):
        print('%s Of%s I am learning%s.' %(self._grade, self._name, course))
            
            
class Teacher(Person):
    '''Teacher'''
    def __init__(self, name, age, title):
        super().__init__(name, age)
        self._title = title

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, title):
        self._title = title

    def teach(self, course):
        print('%s%s Talking about%s.' % (self._name, self._title, course))

        
def main():
    stu = Student('Net big blow', 15, 'Third grade')
    stu.study('Mathematics')
    stu.watch_av()
    t = Teacher('Luo Hao', 38, 'expert')
    t.teach('Pyther Program design')
    t.watch_av

if __name__ == '__main__':
    main()
The net big blow of junior three is learning mathematics
 Netplay can only watch bear touch
 Luo Hao is talking about python programming

exp_2

from abc import ABCMeta, abstractmethod
from random import randint, randrange
class Fighter(object, metaclass = ABCMeta):
    '''Combatants'''
    # Define the variables of the members that the object can do through "slots"
    __slots__  = ('_name', '_hp')
    def __init__(self, name, hp):
        '''Initialization method
        
        :param name: Name
        :param hp: Life value
        '''
        self._name = name
        self._hp = hp
        
    @property
    def name(self):
        return self._name
    
    @property
    def hp(self):
        return self._hp
    
    @hp.setter
    def hp(self, hp):
        self._hp = hp if hp >= 0 else 0
    
    @property
    def alive(self):
        return self._hp > 0
    
    @abstractmethod
    def attack(self, other):
        '''
        //attack
        
        :param other: Target of attack
        '''
        pass
class Ultraman(Fighter):
    """Ultraman"""

    __slots__ = ('_name', '_hp', '_mp')

    def __init__(self, name, hp, mp):
        """Initialization method

        :param name: Name
        :param hp: Life value
        :param mp: Magic value
        """
        super().__init__(name, hp)
        self._mp = mp

    def attack(self, other):
        other.hp -= randint(15, 25)

    def huge_attack(self, other):
        """Research must kill skill(Kill at least 50 or three-quarters of your opponent's blood)

        :param other: Target of attack

        :return: Use success return True Otherwise return False
        """
        if self._mp >= 50:
            self._mp -= 50
            injury = other.hp * 3 // 4
            injury = injury if injury >= 50 else 50
            other.hp -= injury
            return True
        else:
            self.attack(other)
            return False

    def magic_attack(self, others):
        """Magic attack

        :param others: Attacked group

        :return: Use magic to return successfully True Otherwise return False
        """
        if self._mp >= 20:
            self._mp -= 20
            for temp in others:
                if temp.alive:
                    temp.hp -= randint(10, 15)
            return True
        else:
            return False

    def resume(self):
        """Restore mana"""
        incr_point = randint(1, 10)
        self._mp += incr_point
        return incr_point

    def __str__(self):
        return '~~~%s Ultraman~~~\n' % self._name + \
            'Life value: %d\n' % self._hp + \
            'Magic value: %d\n' % self._mp


class Monster(Fighter):
    """Little monster"""

    __slots__ = ('_name', '_hp')

    def attack(self, other):
        other.hp -= randint(10, 20)

    def __str__(self):
        return '~~~%s Little monster~~~\n' % self._name + \
            'Life value: %d\n' % self._hp


def is_any_alive(monsters):
    """Judge if there are any monsters alive"""
    for monster in monsters:
        if monster.alive > 0:
            return True
    return False


def select_alive_one(monsters):
    """Pick a living little monster"""
    monsters_len = len(monsters)
    while True:
        index = randrange(monsters_len)
        monster = monsters[index]
        if monster.alive > 0:
            return monster


def display_info(ultraman, monsters):
    """Display information about Altman and the little monster"""
    print(ultraman)
    for monster in monsters:
        print(monster, end='')


def main():
    u = Ultraman('Luo Hao', 1000, 120)
    m1 = Monster('Di Ren Jie', 250)
    m2 = Monster('Bai Yuan Fang', 500)
    m3 = Monster('Wang Da hammer', 750)
    ms = [m1, m2, m3]
    fight_round = 1
    while u.alive and is_any_alive(ms):
        print('========The first%02d round========' % fight_round)
        m = select_alive_one(ms)  # Pick a little monster
        skill = randint(1, 10)   # Choose which skill to use by random number
        if skill <= 6:  # 60% chance to use normal attack
            print('%s Hit with normal attack%s.' % (u.name, m.name))
            u.attack(m)
            print('%s The magic value of%d spot.' % (u.name, u.resume()))
        elif skill <= 9:  # 30% chance to use magic attack (may fail due to lack of magic)
            if u.magic_attack(ms):
                print('%s Magic attack used.' % u.name)
            else:
                print('%s Failed to use magic.' % u.name)
        else:  # 10% chance to use critical kill skill (use normal attack if magic value is insufficient)
            if u.huge_attack(m):
                print('%s It's a killing skill%s.' % (u.name, m.name))
            else:
                print('%s Hit with normal attack%s.' % (u.name, m.name))
                print('%s The magic value of%d spot.' % (u.name, u.resume()))
        if m.alive > 0:  # If the chosen monster doesn't die, fight back at Altman
            print('%s Hit back.%s.' % (m.name, u.name))
            m.attack(u)
        display_info(u, ms)  # At the end of each round, display information about Altman and the little monster
        fight_round += 1
    print('\n========End of battle!========\n')
    if u.alive > 0:
        print('%s Altman victory!' % u.name)
    else:
        print('Little monster wins!')


if __name__ == '__main__':
    main()
========Round 01========
Luo Hao hit Wang Dabi with a common attack
 Luo Hao's mana has been restored to 7
 Wang dashed back at Luo Hao
 ~~~Luohao Altman~~~
Health: 989
 Mana: 127

~~~Di Renjie little monster~~~
Health: 250
 ~~~Baiyuanfang little monster~~~
HP: 500
 ~~~Wang Dashi small monster~~~
Health: 726
 ========Round 02========
Luo Hao hit Di Renjie with a common attack
 Luo Hao's mana has been restored to 4
 Di Renjie strikes back at Luo Hao
 ~~~Luohao Altman~~~
Health: 972
 Mana: 131

~~~Di Renjie little monster~~~
Health: 233
 ~~~Baiyuanfang little monster~~~
HP: 500
 ~~~Wang Dashi small monster~~~
Health: 726
 ========Round 03========
Luo Hao used the technique of "research must kill" to abuse Wang Da hammer
 Wang dashed back at Luo Hao
 ~~~Luohao Altman~~~
Health: 952
 Magic value: 81

~~~Di Renjie little monster~~~
Health: 233
 ~~~Baiyuanfang little monster~~~
HP: 500
 ~~~Wang Dashi small monster~~~
Health: 182

...
...
...

========Round 34========
Luo Hao hit Di Renjie with a common attack
 Luo Hao's mana has been restored to 3
 Di Renjie strikes back at Luo Hao
 ~~~Luohao Altman~~~
Health: 529
 Mana: 23

~~~Di Renjie little monster~~~
Life value: 2
 ~~~Baiyuanfang little monster~~~
Life value: 0
 ~~~Wang Dashi small monster~~~
Life value: 0
 ========Round 35========
Luo Hao hit Di Renjie with a common attack
 Luo Hao's mana has been restored by 2
 ~~~Luohao Altman~~~
Health: 529
 Mana: 25

~~~Di Renjie little monster~~~
Life value: 0
 ~~~Baiyuanfang little monster~~~
Life value: 0
 ~~~Wang Dashi small monster~~~
Life value: 0

========The battle is over========

Luohao Altman wins!

exp_3

import random


class Card(object):
    """A card"""

    def __init__(self, suite, face):
        self._suite = suite
        self._face = face

    @property
    def face(self):
        return self._face

    @property
    def suite(self):
        return self._suite

    def __str__(self):
        if self._face == 1:
            face_str = 'A'
        elif self._face == 11:
            face_str = 'J'
        elif self._face == 12:
            face_str = 'Q'
        elif self._face == 13:
            face_str = 'K'
        else:
            face_str = str(self._face)
        return '%s%s' % (self._suite, face_str)
    
    def __repr__(self):
        return self.__str__()


class Poker(object):
    """A deck of cards"""

    def __init__(self):
        self._cards = [Card(suite, face) 
                       for suite in '♠♥♣♦'
                       for face in range(1, 14)]
        self._current = 0

    @property
    def cards(self):
        return self._cards

    def shuffle(self):
        """Shuffle the cards(Random disorder)"""
        self._current = 0
        random.shuffle(self._cards)

    @property
    def next(self):
        """Licensing"""
        card = self._cards[self._current]
        self._current += 1
        return card

    @property
    def has_next(self):
        """Are there any cards"""
        return self._current < len(self._cards)


class Player(object):
    """Game player"""

    def __init__(self, name):
        self._name = name
        self._cards_on_hand = []

    @property
    def name(self):
        return self._name

    @property
    def cards_on_hand(self):
        return self._cards_on_hand

    def get(self, card):
        """Touch card"""
        self._cards_on_hand.append(card)

    def arrange(self, card_key):
        """Players organize their cards"""
        self._cards_on_hand.sort(key=card_key)


# Sorting rules - sort by decors and then by points
def get_key(card):
    return (card.suite, card.face)


def main():
    p = Poker()
    p.shuffle()
    players = [Player('East evil'), Player('Western poison'), Player('South Emperor'), Player('Beggar')]
    for _ in range(13):
        for player in players:
            player.get(p.next)
    for player in players:
        print(player.name + ':', end=' ')
        player.arrange(get_key)
        print(player.cards_on_hand)


if __name__ == '__main__':
    main()
Dongxie: [♠ 2, ♠ 3, ♠ 6, ♠ 8, ♣ 5, ♣ 6, ♣ 9, ♠ J, ♠ K, ♠ 5, ♦ 7, ♦ 8, ♦ J]
XD: [♠ A, ♠ 4, ♠ K, ♠ 3, ♣ 4, ♣ 7, ♣ K, ♠ 6, ♠ 2, ♠ 6, ♠ 9, ♣ 10, ♠ Q]
South Emperor: [♠ 5, ♠ 9, ♠ 10, ♠ A, ♣ 2, ♣ 10, ♣ Q, ♣ 3, ♥ 5, ♥ 9, ♣ 10, ♣ 3, ◆ K]
Northern beggar: [♠ 7, ♠ J, ♠ Q, ♣ 8, ♣ J, ♥ A, ♠ 2, ♥ 4, ♥ 7, 󱪅 8, ♥ Q, ♠ A, ◆ 4]

exp_4

### 
"""
//There are three types of employees in a company: Department Manager, programmer and salesman
//A salary settlement system needs to be designed to calculate the monthly salary according to the employee information provided
//The monthly salary of the Department Manager is fixed at 15000 yuan per month
//The programmer's monthly salary is 150 yuan per hour based on the working hours of this month
//The salesperson's monthly salary is 1200 yuan plus 5% of the sales
"""
from abc import ABCMeta, abstractmethod


class Employee(object, metaclass=ABCMeta):
    """staff"""

    def __init__(self, name):
        """
        //Initialization method

        :param name: Full name
        """
        self._name = name

    @property
    def name(self):
        return self._name

    @abstractmethod
    def get_salary(self):
        """
        //Get a monthly salary

        :return: A monthly salary
        """
        pass


class Manager(Employee):
    """Division Manager"""

    def get_salary(self):
        return 15000.0


class Programmer(Employee):
    """Programmer"""

    def __init__(self, name, working_hour=0):
        super().__init__(name)
        self._working_hour = working_hour

    @property
    def working_hour(self):
        return self._working_hour

    @working_hour.setter
    def working_hour(self, working_hour):
        self._working_hour = working_hour if working_hour > 0 else 0

    def get_salary(self):
        return 150.0 * self._working_hour


class Salesman(Employee):
    """Salesperson"""

    def __init__(self, name, sales=0):
        super().__init__(name)
        self._sales = sales

    @property
    def sales(self):
        return self._sales

    @sales.setter
    def sales(self, sales):
        self._sales = sales if sales > 0 else 0

    def get_salary(self):
        return 1200.0 + self._sales * 0.05


def main():
    emps = [
        Manager('Liu Bei'), Programmer('Zhu Geliang'),
        Manager('Cao Cao'), Salesman('Emperor Xu'),
        Salesman('Lv Bu'), Programmer('Zhang Liao'),
        Programmer('Zhao Yun')
    ]
    for emp in emps:
        if isinstance(emp, Programmer):
            emp.working_hour = int(input('Please input%s Working hours of this month: ' % emp.name))
        elif isinstance(emp, Salesman):
            emp.sales = float(input('Please input%s Sales this month: ' % emp.name))
        # It also receives the message get salary, but different employees show different behaviors (polymorphism)
        print('%s The salary of this month is: ¥%s element' %
              (emp.name, emp.get_salary()))


if __name__ == '__main__':
    main()
Liu Bei's salary this month is RMB 15000.0
Published 182 original articles, won praise 104, visited 200000+
Private letter follow

Tags: Python Programming

Posted on Wed, 15 Jan 2020 03:22:21 -0500 by chrisdburns