简体   繁体   English

如何从另一个模块导入类中的函数

[英]How to import a function in class from another module

Module1.py

Class A ():
   def func1(self,...):
      .....


   def func2(self,...):
      .....

Module2.py

   def callfunc():
      How to call func2() from Module1.py

In Module2.py, I tried using在 Module2.py 中,我尝试使用

from Module1 import A

       def callfunc():
          A.func2()

but it throws an error stating TypeError: unbound method **func2()** must be called with **A** instance as first argument (got list instance instead)但它抛出一个错误,指出TypeError: unbound method **func2()** must be called with **A** instance as first argument (got list instance instead)

Could someone tell me how to call func2() in Module2.py ?有人能告诉我如何在 Module2.py 中调用 func2() 吗?

Your import is fine, the problem is that you need an instance of A to call the function from你的import很好,问题是你需要一个A的实例来调用函数

def callfunc():
    a = A()
    a.func2()

This is because func2 is a bound method , in other words it needs an instance of the class to operate on, hence the self argument.这是因为func2一个绑定方法,换句话说,它需要一个类的实例来操作,因此需要self参数。

def func2(self,...):

For you to be able to call it off the class itself, it would be a static function and wouldn't require an instance of the class为了能够从类本身调用它,它将是一个静态函数并且不需要类的实例

def func2():

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

相关问题 将一个模块中的类中的函数中的变量导入另一个模块中 - Import a variable in a function in a class in one module to another 如何从另一个文件中的类模块导入python中的全局变量? - How to import global variables in python from a class module in another file? 从导入另一个模块的类的模块导入函数时的Python导入错误(ModuleNotFoundError) - Python Import Error (ModuleNotFoundError) when importing a function from a module that imports a class from another module Python:如何从依赖于模块的另一个文件中正确导入函数 - Python: how to properly import a function from another file that depends on module 如何将 function 中的列表导入另一个 python 模块? - How to import a list from within a function into another python module? 从另一个模块导入类变量 - Import a class variable from another module 强制从另一个模块中的功能导入 - Force import from a function in another module 如何从另一个文件的主 function 内部导入 Class? - How to Import Class From Inside the Main function of another file? 从 python 中我的模块中的另一个文件夹导入模块 function - Import a module function from another folder in my module in python 如何从另一个模块导入对象作为列表 - How to import objects from another module as a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM