Python初学者必问:如何创建和调用模块?

原创 旧城等待, 2025-01-23 08:45 45阅读 0赞

在 Python 中,模块(Module)是组织代码的单元,它包含函数、类和常量等。以下是如何创建和调用模块的基本步骤:

  1. 创建模块
    • 创建一个.py文件,这个文件将作为你的模块。
    • 编写你想要放入该模块的代码。
  1. # example_module.py
  2. def greet(name):
  3. return f"Hello, {name}!"
  4. class Person:
  5. def __init__(self, name):
  6. self.name = name
  7. def introduce(self):
  8. return f"My name is {self.name}."
  9. GREET_NAME = "Alice"
  10. example_greeting = greet(GREET_NAME))
  11. person_instance = Person(GREET_NAME))
  12. print(example_greeting) # Output: Hello, Alice!
  13. print(person_instance.introduce()) # Output: My name is Alice.
  1. 导入模块
    • 在其他 Python 文件中,想要使用这个模块中的功能,需要首先导入该模块。
  1. # main.py
  2. import example_module
  3. greeting_name = "Bob"
  4. example_greeting = example_module.greet(greeting_name))
  5. print(example_greeting) # Output: Hello, Bob!

以上就是在 Python 中创建和调用模块的基本步骤。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,45人围观)

还没有评论,来说两句吧...

相关阅读