Cod*_*lus 0 python module class
我在模块中有模块Test.py和类测试.这是代码:
class test:
SIZE = 100;
tot = 0;
def __init__(self, int1, int2):
tot = int1 + int2;
def getTot(self):
return tot;
def printIntegers(self):
for i in range(0, 10):
print(i);
Run Code Online (Sandbox Code Playgroud)
现在,在翻译我尝试:
>>> import Test
>>> t = test(1, 2);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
t = test(1, 2);
NameError: name 'test' is not defined
Run Code Online (Sandbox Code Playgroud)
我哪里做错了?
您必须像这样访问该类:
Test.test
Run Code Online (Sandbox Code Playgroud)
如果您想要像以前一样访问该类,您有两种选择:
from Test import *
Run Code Online (Sandbox Code Playgroud)
这会导入模块中的所有内容.但是,不建议这样做,因为模块中的某些内容可能会在没有意识到的情况下覆盖内置函数.
你也可以这样做:
from Test import test
Run Code Online (Sandbox Code Playgroud)
这样更安全,因为你知道要覆盖哪些名称,假设你实际上覆盖了任何东西.
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |