python中模块和包


# 模块 module


def my_sum(*args):                                # 求和函数

    result = 0
    for item in args:
        result += item

    return result


# print(my_sum(1, 2, 3, 4))                       # 10


def my_max(*args):                                # 打印最大值标志----此处仅仅打印一点内容
    print("最大值")


def my_min(*args):
    print("最小值")


class People:                                    # 定义一个类

    def __index__(self, name, age):
        self.name = name
        self.age = age


MAX_NUM = 100                                    # 定义一个变量

以上的函数或者类可能在其他的.py文件中也会用到,那么我就就应该让上述 内容可以被其他文件使用.这种方法相当于C语言中的头文件

我么在工程中添加一个.py文件,将你要共用的函数放进去

这样可以新建一个包,取名为demo,把helloworld.py文件向demo上面拖动

在helloworld上新建一个.py文件,该文件和demo在同一级目录里面

在test.py中输入如下内容


from demo.helloworld import my_sum

print(my_sum(1, 2, 3, 4, 5))                # 15 可以使用helloworld.py中定义的求和函数

猜你喜欢

转载自blog.csdn.net/sehanlingfeng/article/details/92433950
今日推荐