[英]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.