Python 多文件编程。

1.什么是多文件编程?

如果把一些函数或者是类写在同一个文件中,就会显得难以维护,无论是阅读体验还是修改和维护。如此,我们需要将多个py文件写到不同的文件中,每个文件写不同的功能,如此提高了py文件的可维护性和可扩展性。

比如如下项目:

 我们规定,其中的main.py是整个项目程序的入口,程序从这里开始也从这里结束,Core文件夹中存放了这个项目的核心代码和核心功能,而modules文件夹中存放的是一些必要的基本程序,而Init文件夹提供的是对整个项目初始化的功能。

目录如下:

2.实现文件之间函数和类之间的调用。

main.py  代码如下:

# 导入Inits文件夹中的 init文件。
from Inits import init

if __name__ == '__main__':

#   使用init.py中的类:Init()
    init.Init();



    print("start");

init.py代码如下:

import Core.map
from Core import NPC
from Core import player as ply
# 使用语句 :import 导入当前目录的函数或者是类。

# 比如:import Core.map

# 意思是导入Core的map 文件。

# 使用语句:from 目录 import 文件        来导入函数或者类。

# 比如:from Core import NPC

# 意思是导入Core下的NPC 文件。

# 使用语句:from Core import player as ply

# 意思是:导入Core目录下的player文件,并且把player 命名为 ply来使用。

class Init :
    def __init__(self) -> None:
        
        # 使用 Core文件夹中的map文件的Map类。
        core = Core.map.Map();
        # 使用NPC文件中的类NPC
        npc = NPC.NPC();
        # 使用命令的文件ply中的类Player
        p = ply.Player();



        print("init the map");
        print("init the NPC ");
        print("init the player  ");

        

map.py的代码如下:

# 导入Moudles文件夹下的文件math中的类Math。
from Modules.math import Math;


class Map :
    def __init__(self) -> None:
        # 使用这个类
        Math();
        print("This is map class");

 NPC.py代码如下:

# 导入Moudles文件夹下的文件math中的类Math。
from Modules.math import Math

class NPC :
    def __init__(self) -> None:
        # 使用这个类
        Math();
        print("This is not player charactor ");

player.py        代码如下:

# 导入Moudles文件夹下的文件math中的类Math。


from Modules.math import Math


class Player :
    def __init__(self) -> None:
        # 使用Math这个类。
        Math();
        print("This is class Player");

math.py代码如下:


class Math :

    def __init__(self) -> None:
        pass
    
    def add(a,b):
        return a+b;
    def multiply(a,b):
        return a*b;

    def devision(a,b):
        return a/b;

    def sub(a,b):
        return a-b;

    def index(a,b):
        for i in range(1,b):
            a*=a;
        return a;

            
            

通过以上的代码总结如下:

关键字         import 导入文件或者文件目录。

关键字        from        确定import导入的范围。

关键字        as        给导入的文件或者文件夹命一个名字。

  • 2
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值