day26

作者: 两分与桥 | 来源:发表于2018-04-16 20:18 被阅读9次

    反射,四个方法,hasattr,getattr,setattr,delattr,一切皆对象
    http://www.cnblogs.com/linhaifeng/articles/6204014.html

    动态导入

    #a 下的 test.py 文件
    def test_a():
        print('this is a')
    
    def _test_b():
        print('this is b')
    

    (1)导入模块 from xxx import *

    from a.test import *
    
    test_a()
    test_b()
    
    输出结果:
    #找不到 test_b 函数,就算改成_test_b 也是一样
    NameError: name 'test_b' is not defined 
    Process finished with exit code 1
    

    (2)导入模块 __import__('a.test')

    module_t = __import__('a.test') #传入字符串
    print(module_t)  #定位到 test 文件的顶级目录 a
    module_t.test.test_a()
    module_t.test._test_b()  #私有函数也可调用
    
    输出结果:
    <module 'a' (namespace)>  # a 目录
    this is a
    this is b
    

    (3)导入模块 importlib

    import importlib
    
    module_t = importlib.import_module('a.test')
    print(module_t)  #直接定位到 test 
    module_t.test_a()
    module_t._test_b()
    
    输出结果:
    <module 'a.test' from 'C:\\Users\\libai\\PycharmProjects\\begin\\a\\test.py'> #a.test
    this is a
    this is b
    

    __setattr__, __delattr__, __getattr__
    实例化后增加,修改,获取属性时会触发 class 中的这些属性,具体可以看
    http://www.cnblogs.com/linhaifeng/articles/6204014.html

    class Earth:
        start = 0
        def __init__(self, name):
            self.name = name
        def __getattr__(self, item):
            print('this is getattr')
    
    e = Earth('bbs')
    print(e.name)
    e.x  #获取一个不存在的属性,触发__getattr__
    
    输出结果:
    bbs
    this is getattr
    

    获取类的属性

    class Earth:
        start = 0
        def __init__(self, name):
            self.name = name
        def __getattr__(self, item):
            print('this is getattr')
    
    print(Earth.__dict__)  #获取的属性不完整
    print(dir(Earth))   #获取所有的属性
    
    输出结果:
    {'__module__': '__main__', 'start': 0, '__init__': <function Earth.__init__ at 0x000001AE1FC64620>, '__getattr__': <function Earth.__getattr__ at 0x000001AE1FC646A8>, '__dict__': <attribute '__dict__' of 'Earth' objects>, '__weakref__': <attribute '__weakref__' of 'Earth' objects>, '__doc__': None}
    ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'start']
    
    

    包装标准类型

    class List(list):  #继承并修改 list 方法
        def show_list(self):
            for i in self:
                print(i, end='')
            print('')
        def append(self, object):
            print('append the', object)
            if type(object) == str:
                super(List, self).append(object) #调用父类
            else:
                print('only append str')
    l = List('www.baidu.com')
    l.show_list()
    l.append(123)
    l.append('www.google.com')
    print(l)
    
    输出结果:
    www.baidu.com
    append the 123
    only append str
    append the www.google.com
    ['w', 'w', 'w', '.', 'b', 'a', 'i', 'd', 'u', '.', 'c', 'o', 'm', 'www.google.com']
    
    

    授权,也就是在 class 中调用类似于父类的方法和属性,但不继承于父类

    import time
    class open_file():
        def __init__(self, filename, mode='r', encoding='utf-8'):
            self.file = open(filename, mode, encoding=encoding) #直接调用 open 方法
            self.mode = mode
            self.encoding = encoding
        def write(self, item):
            print(item)
            t = time.strftime('%Y-%m-%d %X')
            self.file.write('%s %s' %(t, item)) #用实例的文件类 self.file 操作
        def read(self):
            print(self.file.read()[0:20]) #截出时间戳
        def __getattr__(self, item):
            print(item)
            return getattr(self.file, item) #返回属性调用
    
    f = open_file('a.txt', 'w+', 'utf-8')
    f.write('ni hao ma')
    f.seek(0)
    f.read()
    
    输出结果:
    ni hao ma
    seek
    2018-04-17 00:18:06 
    

    相关文章

      网友评论

        本文标题:day26

        本文链接:https://www.haomeiwen.com/subject/syxykftx.html