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