improve your python code(2)

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@author: XiangguoSun
@contact: sunxiangguodut@qq.com
@file: suggest2.py
@time: 2017/5/2 10:46
@software: PyCharm
"""
# ex1: 三元操作符 condition? value1:value2
x = 0
y = -2
z = x if x < y else y

# ex2: switch...case
# method1:
n = 2
if n == 0:
    print('Your typed 0.\n')
elif n == 1:
    print('Your typed 0.\n')
elif n == 2:
    print('Your typed 2.\n')
else:
    print('Only single-digit accept.\n')


# method2:
def switch(case):
    """
    switch-case code block
    :param case: your case
    :return: specific function in your case
    """
    return {
        0: 'Your typed 0.\n',
        1: 'Your typed 1.\n',
        2: 'Your typed 2.\n'
    }.get(case, 'Only single-digit accept.\n')      # get your input case and decide which function to do.

print(switch(1))

这里写图片描述
这里写图片描述

这里写图片描述

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@author: XiangguoSun
@contact: sunxiangguodut@qq.com
@file: const.py
@time: 2017/5/2 11:43
@software: PyCharm
"""
class _const:
    class ConstError(TypeError):
        pass

    class ConstCaseError(ConstError):
            pass

    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise(self.ConstError, "Can't change const.{name}".format(name=name))
        if not name.isupper():
            raise(self.ConstCaseError, "const name {name} is not all uppercase".format(name=name))
        self.__dict__[name] = value

import sys
sys.modules[__name__] = _const()
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@author: XiangguoSun
@contact: sunxiangguodut@qq.com
@file: constant.py
@time: 2017/5/2 11:30
@software: PyCharm
"""
import const

const.MY_CONSTANT = 1
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@author: XiangguoSun
@contact: sunxiangguodut@qq.com
@file: TEST.py
@time: 2017/5/2 11:42
@software: PyCharm
"""
from constant import const
print(const.MY_CONSTANT)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值