我导入模块的简单代码有什么问题?
What is wrong with my simple code in importing a module?
我写了下面的简单代码来检查如何导入模块:
#check.py
class Test:
def __init__(self):
self.name = "Name"
def func1(self):
print(self.name)
===============================
import check
check.Test.func1()
but when I run this simple code, I get the error:
Traceback (most recent call last):
File "/Users/mf0016/Desktop/Deep-Reinforcement-Learning-Hands-On-Second-Edition-master/check_1.py", line 4, in <module>
check.Test.func1()
TypeError: func1() missing 1 required positional argument: 'self'
你能帮我理解我的错误吗
Python 自动将在 class 中声明的方法的第一个参数“绑定”到调用它的对象的实例。因此,您必须实例化您的测试 class(即创建一个新的 Test
)以获得此行为。你也可以直接调用它,但在这种情况下,你必须自己提供 self
的值(呵呵)。
import check
t = check.Test() # create a new one
t.func1() #this works, because t is now bound to self
check.Test.func1(t) # this also works; you're binding it manually.
我写了下面的简单代码来检查如何导入模块:
#check.py
class Test:
def __init__(self):
self.name = "Name"
def func1(self):
print(self.name)
===============================
import check
check.Test.func1()
but when I run this simple code, I get the error:
Traceback (most recent call last):
File "/Users/mf0016/Desktop/Deep-Reinforcement-Learning-Hands-On-Second-Edition-master/check_1.py", line 4, in <module>
check.Test.func1()
TypeError: func1() missing 1 required positional argument: 'self'
你能帮我理解我的错误吗
Python 自动将在 class 中声明的方法的第一个参数“绑定”到调用它的对象的实例。因此,您必须实例化您的测试 class(即创建一个新的 Test
)以获得此行为。你也可以直接调用它,但在这种情况下,你必须自己提供 self
的值(呵呵)。
import check
t = check.Test() # create a new one
t.func1() #this works, because t is now bound to self
check.Test.func1(t) # this also works; you're binding it manually.