Python初学者必问:如何创建和调用模块?
在 Python 中,模块(Module)是组织代码的单元,它包含函数、类和常量等。以下是如何创建和调用模块的基本步骤:
- 创建模块:
- 创建一个.py文件,这个文件将作为你的模块。
- 编写你想要放入该模块的代码。
# example_module.py
def greet(name):
return f"Hello, {name}!"
class Person:
def __init__(self, name):
self.name = name
def introduce(self):
return f"My name is {self.name}."
GREET_NAME = "Alice"
example_greeting = greet(GREET_NAME))
person_instance = Person(GREET_NAME))
print(example_greeting) # Output: Hello, Alice!
print(person_instance.introduce()) # Output: My name is Alice.
- 导入模块:
- 在其他 Python 文件中,想要使用这个模块中的功能,需要首先导入该模块。
# main.py
import example_module
greeting_name = "Bob"
example_greeting = example_module.greet(greeting_name))
print(example_greeting) # Output: Hello, Bob!
以上就是在 Python 中创建和调用模块的基本步骤。
还没有评论,来说两句吧...