<jupyter_start><jupyter_text>变量的作用域以及python搜索变量的顺序<jupyter_code>x = 100
def foo():
    global x
    x = 200
    
    def bar():
        x = 300
        print(x)
        
    bar()
    print(x)
    
foo()
print(x)<jupyter_output>300
200
200<jupyter_text>面向对象的三大支柱：封装、继承、多态<jupyter_code>from abc import ABCMeta,abstractmethod
class employee(metaclass = ABCMeta):
    """员工（抽象类）"""
    def __init__(self,name):
        self.name = nmae
        
    @abstractmethod
    def get_salary(self):
        """结算月薪（抽象方法）"""
        pass
    
class manager(employee):
    """部门经理"""
    def get_salary(self):
        return 15000.0
    
class programmer(employee):
    """程序员"""
    def __init__(self,name,working_hours=0):
        self.working_hours = working_hours
        super().__init__(name)
        
    def get_salary(self):
        return 200 * self.working_hours
    
    
class salesman(employee):
    """销售员"""
    def __init__(self,name,sales=0.0):
        self.sales= sales
        super().__init__(name)
        
        
    def get_salary(self):
        return 1800.0 + self.sales * 0.05
    
    
calss employeefactory():
    """创建员工的工厂（工厂模式-通过工厂实现对象使用者和对象之间的解耦合）"""
    @staticmethod
    def create(emp_type, *args, **kwargs):
        """创建员工"""
        emp_type = emp_type.upper()
        emp = None
        if emp_type == 'M':
            emp = Manager(*args, **kwargs)
        elif emp_type == 'P':
            emp = Programmer(*args, **kwargs)
        elif emp_type == 'S':
            emp = Salesman(*args, **kwargs)
        return emp
from abc import ABCMeta, abstractmethod



class Employee(metaclass=ABCMeta):
    """员工(抽象类)"""

    def __init__(self, name):
        self.name = name

    @abstractmethod
    def get_salary(self):
        """结算月薪(抽象方法)"""
        pass


class Manager(Employee):
    """部门经理"""

    def get_salary(self):
        return 15000.0


class Programmer(Employee):
    """程序员"""

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

    def get_salary(self):
        return 200.0 * self.working_hour


class Salesman(Employee):
    """销售员"""

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

    def get_salary(self):
        return 1800.0 + self.sales * 0.05


class EmployeeFactory():
    """创建员工的工厂（工厂模式 - 通过工厂实现对象使用者和对象之间的解耦合）"""

    @staticmethod
    def create(emp_type, *args, **kwargs):
        """创建员工"""
        emp_type = emp_type.upper()
        emp = None
        if emp_type == 'M':
            emp = Manager(*args, **kwargs)
        elif emp_type == 'P':
            emp = Programmer(*args, **kwargs)
        elif emp_type == 'S':
            emp = Salesman(*args, **kwargs)
        return emp


from enum import Enum, unique
import random 
@unique
class Suite(Enum):
    """花色（枚举）"""
    SPADE = 0
    HEART = 1
    CLUB = 2
    DIAMOND = 3

    def __lt__(self, other):
        return self.value < other.value


class Card():
    """牌"""
    
    def __init__(self, suite, face):
        self.suite = suite
        self.face = face

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        suites = ('♠', '♥', '♣', '♦')
        faces = ('', 'A', '2', '3', '4', '5', '6', 
                 '7', '8', '9', '10', 'J', 'Q', 'K')
        return f'{suites[self.suite.value]} {faces[self.face]}'


class Poker():
    """扑克"""
    
    def __init__(self):
        self.index = 0
        self.cards = [Card(suite, face)
                      for suite in Suite
                      for face in range(1, 14)]

    def shuffle(self):
        """洗牌"""
        self.index = 0
        random.shuffle(self.cards)

    def deal(self):
        """发牌"""
        card = self.cards[self.index]
        self.index += 1
        return card

    @property
    def has_more(self):
        """是否有更多的牌"""
        return self.index < len(self.cards)


class Player():
    """玩家"""

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

    def get_card(self, card):
        """摸牌"""
        self.cards.append(card)

    def arrange(self):
        """整理手上的牌"""
        self.cards.sort(key=lambda card: (card.suite, card.face))


def main():
    """主函数"""
    poker = Poker()
    poker.shuffle()
    players = [
        Player('东邪'), Player('西毒'), 
        Player('南帝'), Player('北丐')
    ]
    while poker.has_more:
        for player in players:
            player.get_card(poker.deal())
    for player in players:
        player.arrange()
        print(player.name, end=': ')
        print(player.cards)


if __name__ == '__main__':
    main()<jupyter_output>东邪: [♠ 4, ♠ 5, ♠ J, ♠ Q, ♠ K, ♥ 2, ♥ 4, ♥ 6, ♥ K, ♣ 3, ♣ J, ♣ K, ♦ Q]
西毒: [♠ 2, ♠ 6, ♠ 8, ♣ A, ♣ 2, ♣ 4, ♣ 8, ♣ Q, ♦ A, ♦ 8, ♦ 9, ♦ 10, ♦ J]
南帝: [♠ 3, ♠ 9, ♥ 5, ♥ 8, ♥ 10, ♥ J, ♥ Q, ♣ 10, ♦ 2, ♦ 5, ♦ 6, ♦ 7, ♦ K]
北丐: [♠ A, ♠ 7, ♠ 10, ♥ A, ♥ 3, ♥ 7, ♥ 9, ♣ 5, ♣ 6, ♣ 7, ♣ 9, ♦ 3, ♦ 4]<jupyter_text>迭代器 - __iter__ / __next__itertools - 生成可迭代序列的工具模块<jupyter_code>import itertools
from math import sqrt
def is_prime(num):
    """判断素数"""
    for factor in range(2,int(sqrt(num) + 1)):
        if num % factor == 0:
            return False
    return True
class PrimeIter(object):
    """素数迭代器"""

    def __init__(self, min_value, max_value):
        assert 2 <= min_value <= max_value
        self.min_value = min_value - 1
        self.max_value = max_value

    def __iter__(self):
        return self

    def __next__(self):
        self.min_value += 1
        while self.min_value <= self.max_value:
            if is_prime(self.min_value):
                return self.min_value
            self.min_value += 1
        raise StopIteration()


class FibIter(object):
    """斐波那契数迭代器"""
    
    def __init__(self, num):
        self.num = num
        self.a, self.b = 0, 1
        self.idx = 0
   
    def __iter__(self):
        return self

    def __next__(self):
        if self.idx < self.num:
            self.a, self.b = self.b, self.a + self.b
            self.idx += 1
            return self.a
        raise StopIteration()
def main():
    prime = PrimeIter(2,10000)
    for val in prime:
        print(prime)
    
if '__name__' == '__main__':
    main()
class A():

    def say_hello(self):
        print('Hello, A')


class B(A):
    pass


class C(A):

    def say_hello(self):
        print('Hello, C')


class D(B, C):
    pass


class SetOnceMappingMixin():
    """自定义混入类"""
    __slots__ = ()

    def __setitem__(self, key, value):
        if key in self:
            raise KeyError(str(key) + ' already set')
        return super().__setitem__(key, value)


class SetOnceDict(SetOnceMappingMixin, dict):
    """自定义字典"""
    pass


def main():
    print(D.mro())
    # print(D.__mro__)
    D().say_hello()
    print(SetOnceDict.__mro__)
    my_dict= SetOnceDict()
    my_dict['username'] = 'jackfrued'
    my_dict['username'] = 'hellokitty'


if __name__ == '__main__':
    main()<jupyter_output>[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
Hello, C
(<class '__main__.SetOnceDict'>, <class '__main__.SetOnceMappingMixin'>, <class 'dict'>, <class 'object'>)
{'fraction_non_alphanumeric': 0.15537350735906694, 'fraction_numerical': 0.018883643432379894, 'mean_word_length': 2.133101348412353, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '308739', 'license': 'Apache-2.0', 'n_tokens_mistral': 2848, 'n_tokens_neox': 2746, 'n_words': 639, 'path': 'Day16_6.ipynb', 'repo_name': 'hdbnl1122/python100', 'size': '7202'}