• 面向对象的进阶二


    item系列

    getitem,可以以字典键值对的形式取得值(查)

    class A:
        def __init__(self,name,age,sex):
            self.name=name
            self.age=age
            self.sex=sex
        def __getitem__(self, item):
            return self.__dict__[item]
    a=A('二狗',18,'')
    print(a.name)
    print(a['name'])
    print(a['sex'])
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    二狗
    二狗
    男
    
    Process finished with exit code 0

    setitem(增)

    可以以键值对的形式添加

    class A:
        def __init__(self,name,age,sex):
            self.name=name
            self.age=age
            self.sex=sex
        def __getitem__(self, item):
            return self.__dict__[item]
        def __setitem__(self, key, value):
            self.__dict__[key]=value
    
    a=A('二狗',18,'')
    a['爱好']='睡觉'
    print(a['爱好'])
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    睡觉
    
    Process finished with exit code 0

    delitem通过键的方式删除

    class A:
        def __init__(self,name,age,sex):
            self.name=name
            self.age=age
            self.sex=sex
        def __getitem__(self, item):
            return self.__dict__[item]
        def __setitem__(self, key, value):
            self.__dict__[key]=value
        def __delitem__(self, key):
            del self.__dict__[key]
    
    a=A('二狗',18,'')
    a['爱好']='睡觉'
    del a['爱好']
    print(a.__dict__)
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    {'name': '二狗', 'age': 18, 'sex': ''}
    
    Process finished with exit code 0

    2  __new__方法

    可以新建一个对象,其对象的属性不变,先执行new里的

    class A:
        def __init__(self):
            self.name=1
            print('你好')
        def __new__(cls, *args, **kwargs):
            print('dajiahao ')
            return object.__new__(cls)
    a=A()
    a1=A()
    a2=A()
    a3=A()
    print(a.name)
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    dajiahao 
    你好
    dajiahao 
    你好
    dajiahao 
    你好
    dajiahao 
    你好
    1

    这里说一个设计模式:

    单例模式

    从始至终操作的一直是一个对象,当后来的新对象的属性和之前一样的时候

    就覆盖之前的属性,不一样的话就保留

    有则覆盖,无则添加

    class A:
        __in = False
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def __new__(cls, *args, **kwargs):
            if cls.__in:
                print(cls.__in)
                return cls.__in
            cls.__in = object.__new__(cls)
            return cls.__in
    a=A('二狗',18)
    a1=A('',18)
    a.sex=''
    print(a.name)
    print(a1.name)
    print(a1.sex)
    <__main__.A object at 0x000002255E3EDD30>
    狗
    狗
    男
    
    Process finished with exit code 0

    __eq__

    ,即使对象不一样只要是传的值一样,最后内存地址就一样

    class A:
        def __init__(self,name):
            self.name=name
        def __eq__(self, other):
            if self.__dict__==other.__dict__:
                return True
            else:
                return False
    a=A('hh')
    a1=A('gg')
    print(a==a1)
    a=A('hh')
    a1=A('hh')
    print(a==a1)
    a=A('hh')
    a=A('gg')
    print(a==a)
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    False
    True
    True
    
    Process finished with exit code 0

    __hash__

    class A:
        def __init__(self,name,sex):
            self.name=name
            self.sex=sex
        def __hash__(self):
            return hash(str(self.name)+str(self.sex))
    a=A('二狗','')
    a1=A('大狗','')
    print(hash(a))
    print(hash(a1))
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    8933739916456817652
    6638030369082061954
    
    Process finished with exit code 0

    set依赖对象,,hash,,eq

    class A:
        def __init__(self,name,sex,age):
            self.name = name
            self.sex = sex
            self.age = age
    
        def __eq__(self, other):
            if self.name == other.name and self.sex == other.sex:
                return True
            return False
    
        def __hash__(self):
            return hash(self.name + self.sex)
    a = A('二狗','',38)
    b = A('二狗','',37)
    print(set((a,b)))  
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    {<__main__.A object at 0x00000233469AD6D8>}
    
    Process finished with exit code 0

    纸牌游戏

    import json
    from collections import namedtuple
    card=namedtuple('card',['rank','suit'])
    class A:
        ranks=[str(i) for i in range(2,11)]+list('JQKA')
        suits=['红心','方板','梅花','黑桃']
        def __init__(self):
            self._cards=[card(rank,suit) for rank in A.ranks for suit in A.suits]
        def __len__(self):
            return len(self._cards)
        def __getitem__(self, item):
            return self._cards[item]
        def __setitem__(self, key, value):
            self._cards[key] = value
        def __str__(self):
            return json.dumps(self._cards,ensure_ascii=False)
    
    
    a=A()
    print(a[10])
    from random import choice
    print(choice(a))
    from random import shuffle
    shuffle(a)
    print(a[10])
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    card(rank='4', suit='梅花')
    card(rank='5', suit='梅花')
    card(rank='8', suit='黑桃')
    
    Process finished with exit code 0

    3   摘要算法

    hashlib

    import hashlib
    md5=hashlib.md5()
    md5.update(b'123')
    md5=md5.hexdigest()
    print(md5)
    202cb962ac59075b964b07152d234b70
    
    Process finished with exit code 0

    加盐

    import hashlib
    md5=hashlib.md5(bytes('ni',encoding='utf-8'))
    md5.update(b'123')
    md5=md5.hexdigest()
    print(md5)
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    6e17fe6b555ea6041f5e9d9f93819316
    
    Process finished with exit code 0

    动态加盐

    import hashlib
    md5=hashlib.md5(bytes('ni',encoding='utf-8')+b'7')
    md5.update(b'123')
    md5=md5.hexdigest()
    print(md5)
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe C:/s9/day28/jinjie.py
    39b908f762569e157bb988ea3b466698
    
    Process finished with exit code 0

    用户登录

    import hashlib
    usr = input('name')
    password = input('password')
    with open('nn') as f:
        for line in f:
            user,passwd,rr= line.split('|')
            md5 = hashlib.md5()
            md5.update(bytes(password,encoding='utf-8'))
            md5_pwd = md5.hexdigest()
    
            if usr == user and md5_pwd==passwd:
                print('ok')
            else:
                print('NO')
    namea
    password123
    ok

     模块

    configparser模块

    生成文档

    import configparser
    config=configparser.ConfigParser()
    config['AA']={'a':'1'
                    ,'b':'2'
                  ,'c':'3'}
    config['bb']={'aa':'11','bb':'22'}
    with open ('cc.ini','w')as f:
        config.write(f)

    显示文件内的组名

    对象名.sections()

    列表的形式显示

    import configparser
    config=configparser.ConfigParser()
    config['AA']={'a':'1'
                    ,'b':'2'
                  ,'c':'3'}
    config['bb']={'aa':'11','bb':'22'}
    with open ('cc.ini','w')as f:
        config.write(f)
        
        
    print(config.sections())
    ['AA', 'bb']
    
    Process finished with exi

    另一种情况:创建完文件,在新的页面读取

    这个时候读出来的是空列表【】

    import configparser
    config=configparser.ConfigParser()
    print(config.sections())
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe "C:/s9/day29/mokuia .py"
    []
    
    Process finished with exit code 0

    先要读出,然后就可以了

    import configparser
    config=configparser.ConfigParser()
    print(config.sections())
    config.read('cc.ini')
    print(config.sections())
    []
    ['AA', 'bb']

    判断一个组名在不在文件里,在返回True反之False

    import configparser
    config=configparser.ConfigParser()
    config.read('cc.ini')
    print(config.sections())
    print('bb' in config)
    print('bbc' in config)
    ['AA', 'bb']
    True
    False
    
    Process finished with exit code 0

    取字典里的值

    import configparser
    config=configparser.ConfigParser()
    config.read('cc.ini')
    print(config['bb']['aa'])
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe "C:/s9/day29/mokuia .py"
    11
    
    Process finished with exit code 0

    如果没有键就会返回:

    import configparser
    config=configparser.ConfigParser()
    config.read('cc.ini')
    print(config['bb'])
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe "C:/s9/day29/mokuia .py"
    <Section: bb>
    
    Process finished with exit code 0

    for i in的应用

    import configparser
    config=configparser.ConfigParser()
    config.read('cc.ini')
    for k in config['bb']:
        print(k)
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe "C:/s9/day29/mokuia .py"
    aa
    bb
    
    Process finished with exit code 0

    options和for循环一样,只是不同的是打印出来的键是存放在列表里的

    import configparser
    config=configparser.ConfigParser()
    config.read('cc.ini')
    print(config.options('bb'))
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe "C:/s9/day29/mokuia .py"
    ['aa', 'bb']
    
    Process finished with exit code 0

    打印键值对

    C:UsershcAppDataLocalProgramsPythonPython36python3.exe "C:/s9/day29/mokuia .py"
    ['aa', 'bb']
    
    Process finished with exit code 0
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe "C:/s9/day29/mokuia .py"
    [('aa', '11'), ('bb', '22')]
    
    Process finished with exit code 0

    get找键对应的值

    import configparser
    config=configparser.ConfigParser()
    config.read('cc.ini')
    print(config.get('bb','aa'))
    print(config.get('bb','bb'))
    C:UsershcAppDataLocalProgramsPythonPython36python3.exe "C:/s9/day29/mokuia .py"
    11
    22
    
    Process finished with exit code 0

    import configparser
    config=configparser.ConfigParser()
    config.read('cc.ini')
    config.add_section('89')

    import configparser
    config=configparser.ConfigParser()
    config.read('cc.ini')
    config.remove_section('bb')
    config.remove_option('AA','a')
    config.write(open('new.ini','w'))

    import configparser
    config=configparser.ConfigParser()
    config.read('cc.ini')
    config.set('bb','cc','33')
    config.write(open('new.ini','w'))

    logging,模块

    灵活配置日志级别,,格式,输出位置

    import logging
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s   %(filename)s [line:%(lineno)d]  %(levelname)s',
                        datefmt='%a  %d   %b  %Y   %H:%M:%S',
                        filename='ll',
                        filemode='w'
                        )
    
    
    
    
    logging.debug('debug  message')
    logging.info('zhengchang  message')
    logging.warning('warn  message')
    logging.error('cuowu,  message')
    logging.critical('zhongyao   message')

    配置参数

    logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:
    
    filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
    filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
    format:指定handler使用的日志显示格式。
    datefmt:指定日期时间格式。
    level:设置rootlogger(后边会讲解具体概念)的日志级别
    stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
    
    format参数中可能用到的格式化串:
    %(name)s Logger的名字
    %(levelno)s 数字形式的日志级别
    %(levelname)s 文本形式的日志级别
    %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
    %(filename)s 调用日志输出函数的模块的文件名
    %(module)s 调用日志输出函数的模块名
    %(funcName)s 调用日志输出函数的函数名
    %(lineno)d 调用日志输出函数的语句所在的代码行
    %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
    %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
    %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
    %(thread)d 线程ID。可能没有
    %(threadName)s 线程名。可能没有
    %(process)d 进程ID。可能没有
    %(message)s用户输出的消息

    log对象配置

    import logging
    log=logging.getLogger()
    h=logging.FileHandler('test.log',encoding='utf-8')#创建文件,写入日志
    h1=logging.StreamHandler()#用于控制台的输出
    formate=logging.Formatter('%(asctime)s   %(filename)s [line:%(lineno)d]  %(levelname)s')
    h.setLevel(logging.DEBUG)
    h.setFormatter(formate)
    h1.setFormatter(formate)
    log.addHandler(h)
    log.addHandler(h1)
    logging.debug('debug  message')
    logging.info('zhengchang  message')
    logging.warning('warn  message')
    logging.error('cuowu,  message')
    logging.critical('zhongyao   message')
    2018-01-24 15:13:43,331   mokuia .py [line:44]  WARNING
    2018-01-24 15:13:43,332   mokuia .py [line:45]  ERROR
    2018-01-24 15:13:43,332   mokuia .py [line:46]  CRITICAL
    
    Process finished with exit code 0
  • 相关阅读:
    C++元编程和Boost编程库 (C++ Metaprogramming and Boost MPL )中部
    支持插件的消息中间件【msg broker with plugin】 知然 博客园
    sync date
    Rubular: a Ruby regular expression editor and tester
    当爬虫被拒绝时(Access Denied) 风中之炎 博客园
    quartz scheduler
    C++ 使用STL string 实现的split,trim,replace修订
    java脚本编程 语言、框架与模式
    C++标准转换运算符const_cast
    http://jsoneditoronline.org/
  • 原文地址:https://www.cnblogs.com/xuguangzong/p/8336309.html
Copyright © 2020-2023  润新知