0
這裏是我的兩個文件:無法從另一個文件構造一類
Character.py
def Check_File(fn):
try:
fp = open(fn);
except:
return None;
return fp;
class Character:
## variables ##
## atk ##
## def ##
## HP ##
## empty inv ##
'''
init (self, filename),
RETURN -1 == if the file is not exist
RETURN 0 == all good
all files will be save in format of
"skill: xxx, xxx; xxx, xxx; xxx, xxx;"
'''
def __init__(self, fn):
fp = Check_File(fn);
if(fp == None):
print "Error: no such file"
return None;
self.stats = {};
for line in fp:
nline = line.strip().split(": ");
if(type(nline) != list):
continue;
else:
self.stats[nline[0]] = nline[1];
##print self.stats[nline[0]]
fp.close();
'''
display character
'''
def Display_Character(self):
print "The Character had:";
## Parse into the character class ##
for item in self.stats:
print item + ": " + self.stats[item];
print "Finished Stats Displaying";
print Character("Sample.dat").stats
另一條是:
Interface.py
##from Interface_helper import *;
from Character import *;
wind = Character("Sample.dat");
wind.Display_Character();
當我在Character.py中運行代碼,它給出了
%run "C:/Users/Desktop/Helper Functions/New Folder/Character.py"
{'item': 'weird stuff', 'hp': '100', 'name': 'wind', 'def': '10', 'atk': '10'}
但是當我運行Interface.py:
我
%run "C:/Users/Desktop/Helper Functions/New Folder/Interface.py"
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
E:\canopy\Canopy\App\appdata\canopy-1.4.0.1938.win-x86_64\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
195 else:
196 filename = fname
--> 197 exec compile(scripttext, filename, 'exec') in glob, loc
198 else:
199 def execfile(fname, *where):
C:\Users\Desktop\Helper Functions\New Folder\Interface.py in <module>()
13 from Character import *;
14
---> 15 wind = Character("Sample.dat");
16
17
C:\Users\Desktop\Helper Functions\New Folder\Character.py in __init__(self, fn)
48 for line in fp:
49 nline = line.strip().split(": ");
---> 50 if(type(nline) != list):
51 continue;
52 else:
AttributeError: Character instance has no attribute 'stats'
我想知道是怎麼回事了這一段代碼,爲什麼我輸入了錯誤的方式?
對不起,回覆晚了,這是非常有幫助的,我會去仔細檢查。謝謝。前兩個是我個人對分號和括號的偏好。後兩個真的很有幫助。再次感謝。 – windsound
我又跑了,它的工作原理很奇怪...... – windsound