[Python]小甲鱼Python视频第050课(模块:模块就是程序)课后题及参考解答

 # -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 22:35:20 2019

@author: fengs
"""

"""
测试题(笔试,不能上机哦~)

0. 说到底,Python 的模块是什么?
    函数包,程序包
    
1. 我们现在有一个 hello.py 的文件,里边有一个 hi() 函数:
def hi():
    print("Hi everyone, I love FishC.com!")
    
请问我如何在另外一个源文件 test.py 里边使用 hello.py 的 hi() 函数呢?

    import hello
    hello.hi()
    
2. 你知道的总共有几种导入模块的方法?
    import 模块名 as 新的模块名
    from  模块名 import 模块元素  
    from 模块名 import * 


3. 曾经我们讲过有办法阻止 from…import * 导入你的“私隐”属性,你还记得是怎么做的吗?
    内部属性和内部方法 以  _ 开头
    
4.倘若有 a.py 和 b.py 两个文件,内容如下:


# a.py
def sayHi():
    print("嗨,我是 A 模块~")

# b.py
def sayHi():
    print("嗨,我是 B 模块~")
    
那么我在 test.py 文件中执行以下操作,会打印什么结果?
# test.py
from a import sayHi
from b import sayHi

sayHi()

打印 嗨,我是 B 模块~  后引入的覆盖了先引入ude
  
    
"""

"""
5. 执行下边 a.py 或 b.py 任何一个文件,都会报错,请尝试解释一下此现象。
# a.py
from b import y
def x():
    print('x')

# b.py
from a import x
def y():
    print('y')

>>> 
Traceback (most recent call last):
  File "/Users/FishC/Desktop/a.py", line 1, in <module>
    from b import x
  File "/Users/FishC/Desktop/b.py", line 1, in <module>
    import a
  File "/Users/FishC/Desktop/a.py", line 1, in <module>
    from b import x
ImportError: cannot import name 'x'

1.循环递归import 



"""



"""
动动手

0. 问大家一个问题:Python 支持常量吗?相信很多鱼油的答案都是否定的,但实际上 Python 内建的命名空间是支持一小部分常量的,比如我们熟悉的 True,False,None 等,只是 Python 没有提供定义常量的直接方式而已。
那么这一题的要求是创建一个 const 模块,功能是让 Python 支持常量。
"""
import const1

# const 模块就是这道题要求我们自己写的
# const 模块用于让 Python 支持常量操作

const1.NAME = "FishC"
print(const1.NAME)

try:
    const1.NAME = "FishC.com"
except TypeError as Err:
    print(Err)
print(const1.NAME)

try:
    # 变量名需要大写
    const1.name = "FishC"
except TypeError as Err:
    print(Err)

  

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 01:02:06 2019

@author: fengs
"""

#const1.py

class const1:
    def __setattr__(self,item,value):
        #print(self.__dict__)
        if item in self.__dict__:
            print('err1')
            raise TypeError("常量无法改变")
        elif item.isupper() == False:
            print('err2')
            raise TypeError("常量名必须由大写字母组成!")
        self.__dict__[item] = value
        

import sys
sys.modules[__name__] = const1()


# 该模块用于让 Python 支持常量操作
"""
class const1:    
    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise TypeError('常量无法改变!')
            
        if not name.isupper():
            raise TypeError('常量名必须由大写字母组成!')

        self.__dict__[name] = value

import sys
sys.modules[__name__] = const1()
"""

  

posted @ 2019-03-25 01:41  Alimy  阅读(526)  评论(0编辑  收藏  举报