简体   繁体   English

你能在 python 中“嵌套”模块吗?

[英]Can you "nest" modules in python?

I'm working with a pygame tutorial and I'm importing the pygame module on a separate file from my main.py.我正在使用 pygame 教程,我正在将 pygame 模块导入到我的 main.py 的单独文件中。

pygame.py: pygame.py:

    import pygame

class Game:

    def __init__(self):

main.py:主要.py:

from game import Game

def main():

I'm guessing I already have my answer, since I keep receiving the error: "NameError: name 'pygame' is not defined", but is there any way to nest modules without importing them into your main?我猜我已经有了答案,因为我不断收到错误消息:“NameError: name 'pygame' is not defined”,但是有没有办法嵌套模块而不将它们导入你的主模块? Not a big deal, just thought I'd ask.没什么大不了的,只是想问问。

You might access imported modules inside imported modules following way您可以按照以下方式访问导入模块中的导入模块

mymodule.py我的模块.py

import math
class Math:
    pass

main.py主文件

import mymodule
print(mymodule.math.cos(0.0))

then running python main.py output然后运行python main.py output

1.0

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

相关问题 可以为 Python 中的导入模块定义别名吗? - Can you define aliases for imported modules in Python? 为什么不能在python 3中导入python 2模块? - Why can't you import python 2 modules in python 3? 你能用python连接到web服务,没有外部模块吗? - Can you connect to web service using python, and no external modules? 你怎么能看到你在 Jupyter notebook 中导入的带有星号的 python 模块列表? - How can you see a list of python modules that YOU imported in Jupyter notebook with asterisk? 您可以创建一个 Python 本机命名空间 package ,其中您在命名空间正下方有代码模块吗? - Can you create a Python native namespace package where you have code modules directly below the namespace? 您可以在列表理解中嵌套多少个 for 循环是否有限制? - Is there a limit to how many for loops you can nest in a list comprehension? 如何在 python 中动态导入模块而不是硬编码导入? - How can you dynamically import modules instead of hard-coding import in python? 是否可以始终将JSON对象嵌套在JSON数组中? - Can you always nest a JSON object in a JSON array? 如何让用户轻松地一次安装多个 python 模块? - How can you make it easy for users to install multiple python modules at once? 您应该在哪个目录中安装 python 模块? - In which directory should you install python modules?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM