简体   繁体   English

在python中实例化模块时如何将模块导入类?

[英]How do i import modules into classes when they are instantiated in python?

I have a class "ClassX".我有一个“ClassX”类。 In it are multiple function definitions, each of which use the same module in different ways.其中有多个函数定义,每个函数定义都以不同的方式使用相同的模块。 Let's say that the module being imported is "ModuleY".假设要导入的模块是“ModuleY”。 When i instantiate this class, how do i make it import this module in a way that can be accessed by all of ClassX's functions?当我实例化这个类时,我如何让它以一种可以被所有 ClassX 函数访问的方式导入这个模块? Ie would i import it like this:即我会像这样导入它:

class ClassX():
   def __init__(self):
      import ModuleY

Like this:像这样:

class ClassX():
   import ModuleY
   def __init(self):
      #do something

or would i have to import the module for every function call:或者我是否必须为每个函数调用导入模块:

class ClassX():
   def __init__(self):
      #do something#
   def functionA(self):
      import ModuleY
      #do something
   def functionB(self):
      import ModuleY
      #do something

Just import ModuleY as normal and then refer to the functions within ModuleY as necessary in other parts of your script.只需像往常一样导入 ModuleY,然后在脚本的其他部分根据需要引用 ModuleY 中的函数。

ModuleY.py

def do_something():
    print("something")


main.py 

import ModuleY

class ClassX():
    def __init__(self):
      # do_something()
      # prints "something"

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

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