繁体   English   中英

在Python模块中定义和使用类

[英]defining and using classes in modules for Python

我有模块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);

现在,在解释器中,我尝试:

>>> import Test
>>> t = test(1, 2);

我收到以下错误:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    t = test(1, 2);
NameError: name 'test' is not defined

我哪里做错了?

您必须像这样访问该类:

Test.test

如果要像以前尝试的那样访问该类,则有两个选择:

from Test import *

这将从模块导入所有内容。 但是,不建议这样做,因为模块中的某些内容可能会覆盖内置函数而没有意识到。

您也可以这样做:

from Test import test

这样更安全,因为假设您实际上在覆盖任何内容,那么您就知道要覆盖哪些名称。

@larsmans和@Votatility已经回答了您的问题,但是我很喜欢,因为没有人提到您使用命名约定违反了Python标准

模块应全部使用小写字母,并用下划线分隔(可选),而类应采用驼峰式。 因此,您应该拥有的是:

test.py:

class Test(object):
    pass

其他

from test import Test
# or 
import test
inst = test.Test()

当您import Test ,可以将其作为Test.test进行访问。 如果要作为test访问它,请from Test import test

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM