美文网首页
python语法入门六

python语法入门六

作者: 是我真的是我 | 来源:发表于2019-10-15 16:28 被阅读0次
    • 属性访问
    • 描述符
    • 迭代器
    • 生成器
    • 模块导入
    • 查询功能

    属性访问

    '属性'
    class C:
        def __getattribute__(self, name):
            print('getattribute')
            return super().__getattribute__(name)
        def __getattr__(self, name):
            print('getattr')
        def __setattr__(self, key, value):
            print('setattr')
            super().__setattr__(key, value)
        def __delattr__(self, item):
            print('delattr')
            super().__delattr__(item)
    c = C()
    c.x
    # getattribute
    # getattr
    c.x = 1
    # setattr
    c.x
    # getattribute
    del c.x
    # delattr
    
    class A:
        def __init__(self, name):
            self.name = name
        def __setattr__(self, key, value):
            if key == 'no':
                self.name = 'none'
            else:
                # self.name = value 错误的写法,会无限递归下去
                # 推荐下述写法
                super().__setattr__(key, value)
    

    描述符

    class Celsius:
        def __init__(self, value=26.0):
            self.value = float(value)
    
        def __get__(self, instance, owner):
            return self.value
    
        def __set__(self, instance, value):
            self.value = float(value)
    
    
    class Fahrenheit:
        def __get__(self, instance, owner):
            return instance.cel * 1.8 + 32
    
        def __set__(self, instance, value):
            instance.cel = (float(value) - 32) / 1.8
    
    
    class Temperature:
        cel = Celsius()
        fah = Fahrenheit()
    
    temp = Temperature()
    print(temp.cel)
    # 26.0
    print(temp.fah)
    # 78.80000000000001
    

    定制容器

    '不可变容器'
    class CountList:
        def __init__(self, *args):
            self.values = [x for x in args]
            # count 保存了数被访问的次数
            self.count = {}.fromkeys(range(len(self.values)), 0)
    
        def __len__(self):
            return len(self.values)
    
        def __getitem__(self, index):
            self.count[index] += 1
            return self.values[index]
    
    
    c1 = CountList(1, 2, 3)
    c2 = CountList(4, 5)
    print(c1[1])
    # 2
    print(c2[0])
    # 4
    print(c1.count)
    # {0: 0, 1: 1, 2: 0}
    print(c2.count)
    # {0: 1, 1: 0}
    print(c1[1] + c2[0])
    # 6
    print(c1.count)
    # {0: 0, 1: 2, 2: 0}
    

    迭代器

    string = 'abcdef'
    it = iter(string)
    print(next(it))
    # a
    print(next(it))
    # b
    
    '斐波那契数列'
    class Fibs:
        def __init__(self, n=10):
            self.a = 0
            self.b = 1
            self.n = n
    
        def __iter__(self):
            return self
    
        def __next__(self):
            self.a, self.b = self.b, self.a + self.b
            if self.a > self.n:
                raise StopIteration
            return self.a
    
    fibs = Fibs(100)
    for i in fibs:
        print(i)
    # 1
    # 1
    # 2
    # 3
    # 5
    # 8
    # 13
    # 21
    # 34
    # 55
    # 89
    

    生成器

    def myGen():
        print('生成器被执行')
        yield 1
        yield 2
    
    myG = myGen()
    print(next(myG))
    # 生成器被执行
    # 1
    print(next(myG))
    # 2
    # print(next(myG))
    # 报错 StopIteration
    
    
    def libs():
        a = 0
        b = 1
        while True:
            a, b = b, a + b
            yield a
    
    for i in libs():
        if i > 100:
            break
        print(i, end=' ')
    # 1 1 2 3 5 8 13 21 34 55 89
    
    
    c = {i for i in [1, 1, 2, 3, 4, 4, 5, 1, 3, 6]}
    print(c)
    # {1, 2, 3, 4, 5, 6}
    

    模块导入

    if  __name__ == '__main__' 
    我们简单的理解就是: 如果模块是被直接运行的,则代码块被运行,如果模块是被导入的,则代码块不被运行。
    

    fun.py

    'fun.py 模块'
    def test():
        print('测试方法')
    
    def other():
        print('其他方法')
    
    # __name__ 返回的若是__main__则表示为本模块调用
    # 否则为其他模块调用,返回值为被调用的模块名fun
    if __name__ == '__main__':
        test()
    
    print(__name__)
    other()
    
    
    # 本模块运行结果:
    # 测试方法
    # __main__
    # 其他方法
    

    另一个模块

    import sys
    
    print(sys.path)
    # (表示将从以下目录查找模块)
    # ['E:\\python\\python37.zip', 'E:\\python']
    
    sys.path.append('E:/pycharm/project')
    import fun
    
    
    # 本模块运行结果:
    # ['E:\\python\\python37.zip', 'E:\\python']
    # fun
    # 其他方法
    


    引包引模块
    # 包名为bao,模块名为fun
    import bao.fun as f
    

    查询功能

    import time
    print(time.__doc__)
    # This module provides various functions to...(等介绍)
    print(dir(time))
    # ['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'tzname']
    print(time.__name__)
    # time
    

    相关文章

      网友评论

          本文标题:python语法入门六

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