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

2024-04-19 20:14:16 发布

您现在位置:Python中文网/ 问答频道 /正文

Module1.py

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


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

Module2.py

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

在Module2.py中,我尝试使用

from Module1 import A

       def callfunc():
          A.func2()

但是它抛出了一个错误声明TypeError: unbound method **func2()** must be called with **A** instance as first argument (got list instance instead)

有人能告诉我如何在Module2.py中调用func2()吗?你知道吗


Tags: toinstancefrompyimportselfdefcall
1条回答
网友
1楼 · 发布于 2024-04-19 20:14:16

你的import很好,问题是你需要一个A的实例来调用函数

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

这是因为func2a bound method,换句话说,它需要类的实例来操作,因此self参数。你知道吗

def func2(self,...):

为了能够从类本身调用它,它将是一个静态函数,不需要类的实例

def func2():

相关问题 更多 >