简体   繁体   English

Python3 导入类

[英]Python3 importing classes

I'm just starting to learn python and I thought a good way to practice would be by building a custom linked list class.我刚刚开始学习 python,我认为一个很好的练习方法是构建一个自定义的链表类。 I was able to get my custom list to work properly when everything was in one file.当所有内容都在一个文件中时,我能够让我的自定义列表正常工作。 However, I wanted to practice importing, so I split my code into three files: ListNode.py, mySLL.py, testMySll.py.但是,我想练习导入,因此我将代码拆分为三个文件:ListNode.py、mySLL.py、testMySll.py。 All of these files are under the same directory "codingPractice".所有这些文件都在同一目录“codingPractice”下。 I'm trying to import listNode.py into mySLL.py and mySLL.py into testMySll.py.我正在尝试将 listNode.py 导入 mySLL.py 并将 mySLL.py 导入 testMySll.py。 How would I do this?我该怎么做?

Importing modules in Python is pretty straight forward.在 Python 中导入模块非常简单。 For a thorough explanation see this guide on modules .有关详细说明,请参阅有关模块的指南 However, to give you a quickstart using the examples you provided, you can import modules like this:但是,为了使用您提供的示例快速入门,您可以导入如下模块:

    # importing into mySLL.py
    import listNode

    bar = listNode.func(foo)

The same workflow goes for importing mySSL.py into the testMySll.py file.将 mySSL.py 导入 testMySll.py 文件的工作流程相同。 Keep in mind that imported modules act like objects so you call the functions using module.func and any variables that are global in the module can be called using module.var .请记住,导入的模块就像对象,因此您可以使用module.func调用函数,并且可以使用module.var调用module.func任何全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM