12.Python的高级语法和用法

# from enum import Enum
# 枚举
# class VIP(Enum):
#     YELLOW = 1
#     YELLOW_ALIAS = 1 # 别名
#     GREEN = 2
#     BLACK = 3
#     RED = 4

# print(VIP.GREEN)        # VIP.GREEN8VIP.GREEN
# print(VIP.GREEN.name)   # GREEN
# print(VIP['GREEN'])     # VIP.GREEN

# for v in VIP:
    # print(v)
# VIP.YELLOW
# VIP.GREEN
# VIP.BLACK
# VIP.RED

# for v in VIP.__members__.items():
#     print(v)
# ('YELLOW', <VIP.YELLOW: 1>)
# ('YELLOW_ALIAS', <VIP.YELLOW: 1>)
# ('GREEN', <VIP.GREEN: 2>)
# ('BLACK', <VIP.BLACK: 3>)
# ('RED', <VIP.RED: 4>)

# for v in VIP.__members__:
#     print(v)
# YELLOW
# YELLOW_ALIAS
# GREEN
# BLACK
# RED

# result = VIP.GREEN == VIP.BLACK
# print(result)  # False
# result = VIP.GREEN == 2
# print(result)  # False
# result =VIP.GREEN is VIP.GREEN
# print(result)  # True

# a = 1
# print(VIP(a))  # VIP.YELLOW


# from enum import IntEnum
# class VIP(IntEnum):
#     YELLOW = 1
#     GREEN = 2
#     BLACK = 'str'
#     RED = 4


from enum import IntEnum,unique
@unique
class VIP(IntEnum):
    YELLOW = 1
    GREEN = 2
    BLACK = 1
    RED = 4

 

# 闭包=函数 + 环境变量
# def curve_pre():
#     a = 25 # 环境变量
#     def curve(x):
#         # print('this is a function')
#         return a*x*x
#     return curve

# f = curve_pre()
# print(f(2))   # 100

# b = 10
# def f1(x):
#     return b * x * x
# print(f1(2))  # 40

# a = 10
# f = curve_pre()
# print(f(2))  # 100
# print(f.__closure__)                   # (<cell at 0x00F1C2D0: int object at 0x65DDE490>,)
# print(f.__closure__[0].cell_contents)  # 25

# c = 25
# def curve_pre():
#     def curve(x):
#         # print('this is a function')
#         return c*x*x
#     return curve
# c = 10
# f = curve_pre()
# print(f(2))  # 40


# def f1():
#     a = 10
#     def f2():
#         a = 20
#         print(a)  #2. 20
#     print(a)  #1. 10
#     f2()
#     print(a)  #3. 10

# f1()


# def f1():
#     a = 10
#     def f2():
#         a = 20
#         return a
#     return f2

# f = f1()
# print(f)             # <function f1.<locals>.f2 at 0x02AC5198>
# print(f.__closure__) # None


# def f1():
#     a = 10
#     def f2():
#         return a
#     return f2

# f = f1()
# print(f)             # <function f1.<locals>.f2 at 0x03995198>   
# print(f.__closure__) # (<cell at 0x01E0C270: int object at 0x65DDE3A0>,)



# origin = 0
# def go(step):
#     new_pos = origin + step
#     # origin = new_pos
#     return origin

# print(go(2)) # 0
# print(go(3)) # 0
# print(go(6)) # 0


# 非闭包的实现
# origin = 0
# def go(step):
#     global origin
#     new_pos = origin + step
#     origin = new_pos
#     return origin

# print(go(2)) # 2
# print(go(3)) # 5
# print(go(6)) # 11


# 闭包的实现
origin = 0
def factory(pos):
    def go(step):
        nonlocal pos
        new_pos = pos + step
        pos = new_pos
        return new_pos
    return go

tourist = factory(origin)
print(tourist(2))  # 2
print(tourist(3))  # 5
print(tourist(6))  # 11

 

posted @ 2018-04-21 14:09  邹柯  阅读(217)  评论(0编辑  收藏  举报