先前定义的类方法的名称错误,应存在的索引的IndexError

所以,我在npc.name上收到一个NameError(我想我打算重新定义的所有后续类方法链接的变量中都会出现NameError),而且,我之前也出现了IndexError。

我将详细解释,但首先,我的代码。

这是我的完整代码,当心:

# import pickle
import pickle
npcs_pickle_file = 'NPCatt.pk'
npc_count = 200

class NPC:
    def __init__(self,name="",occupation="",weakness="",need="",desire="",enemy="",rumor="",secret="",passion="",redeeming_quality="",damning_quality="",happy="",occ_desire="",occ_complication="",pc_opinion="",accomplishment="",magical_gear="",political_influence="",resource="",intel="",research=""):

        # Attributes
        self.name = name
        self.occupation = occupation
        self.weakness = weakness
        self.need = need
        self.desire = desire
        self.enemy = enemy
        self.rumor = rumor
        self.secret = secret
        self.passion = passion
        self.redeeming_quality = redeeming_quality
        self.damning_quality=damning_quality
        self.happy = happy
        self.occ_desire = occ_desire
        self.occ_complication = occ_complication
        self.pc_opinion = pc_opinion
        self.accomplishment = accomplishment
        self.magical_gear = magical_gear
        self.political_influence = political_influence
        self.resource = resource
        self.intel = intel
        self.research = research


    def __str__(self):
        npc_output = "####NPC SUMMARY####\n"
        for att,val in self.__dict__.items():
            if val:
                npc_output += (f"{att} = {val}\n")
        return npc_output

# open a pickle file
# load your data back to memory when you need it
try:
    with open(npcs_pickle_file,'rb') as fi:
        npcs = pickle.load(fi)
except FileNotFoundError as fne:
    #file doesnt exist prob first time running so create a dict with the 170 npc id's
    npcs = {id: None for id in range(npc_count)}


#select an NPC to modify / create
npc_id = None
while not npc_id:
    try:
        npc_id = int(input(f"Enter the id number of the NPC you wish to modify: "))
    except ValueError as ve:
        print("You must provide a numerical id")

    if npc_id < 0 or npc_id >= npc_count:
        npc_id = None
        print(f"you must provide a value between 0 and {npc_count}")



if npcs[npc_id]:
    npc = npcs[npc_id]
    print(npc)
    modify = input("This NPC already exists,do you want to continue and change them? (y/n): ")
    if modify.lower() == "y":
        name = input("Enter name of NPC: ") 
        occupation = input("Enter NPC occupation: ")
        weakness= input("Enter Weakness: ")
        need= input("Enter Need: ")
        desire= input("Enter Desire: ")
        enemy= input("Enter Enemy: ")
        rumor= input("Enter Rumor: ")
        secret= input("Enter Secret: ")
        passion= input("Enter Passion: ")
        redeeming_quality=input("Enter Redeeming Quality: ")
        damning_quality=input("Enter Damning Quality: ")
        happy= input("Enter,is this NPC happy?: ")
        occ_desire= input("Enter an Occupational Desire: ")
        occ_complication= input("Enter an Occupational Complication: ")
        pc_opinion= input("Enter this NPC's disposition toward the PCs: ")
        accomplishment= input("Enter an accomplishment: ")
        magical_gear= input("Enter Magical Gear: ")
        political_influence=input("Enter Political Influence: ")
        resource= input("Enter Resource Level: ")
        intel= input("Enter Intel Tier: ")
        research= input("Enter Research: ")

        npc.name = name
        npc.occupation = occupation
        npc.weakness = weakness
        npc.need = need
        npc.desire= desire
        npc.enemy= enemy
        npc.rumor= rumor
        npc.secret= secret
        npc.passion= passion
        npc.redeeming_quality= redeeming_quality
        npc.damning_quality= damning_quality
        npc.happy= happy
        npc.occ_desire=occ_desire
        npc.occ_complication=occ_complication
        npc.pc_opinion=pc_opinion
        npc.accomplishment=accomplishment
        npc.magical_gear=magical_gear
        npc.political_influence=political_influence
        npc.resource=resource
        npc.intel=intel
        npc.research=research


    else:    

        npcs[npc_id] = NPC(name=npc.name,occupation=npc.occupation,weakness=npc.weakness,need=npc.need,desire=npc.desire,\
                       enemy=npc.enemy,rumor=npc.rumor,secret=npc.secret,passion=npc.passion,redeeming_quality=npc.redeeming_quality,\
                       damning_quality=npc.damning_quality,happy=npc.happy,occ_desire=npc.occ_desire,\
                       occ_complication=npc.occ_complication\,pc_opinion=npc.pc_opinion,accomplishment=npc.accomplishment,\
                       magical_gear=npc.magical_gear,political_influence=npc.political_influence,resource=npc.resource,\
                       intel=npc.intel,research=npc.research)
else:
    name = input("Enter name of NPC: ") 
    occupation = input("Enter NPC occupation: ")
    weakness= input("Enter Weakness: ")
    need= input("Enter Need: ")
    desire= input("Enter Desire: ")
    enemy= input("Enter Enemy: ")
    rumor= input("Enter Rumor: ")
    secret= input("Enter Secret: ")
    passion= input("Enter Passion: ")
    redeeming_quality=input("Enter Redeeming Quality: ")
    damning_quality=input("Enter Damning Quality: ")
    happy= input("Enter,is this NPC happy?: ")
    occ_desire= input("Enter an Occupational Desire: ")
    occ_complication= input("Enter an Occupational Complication: ")
    pc_opinion= input("Enter this NPC's disposition toward the PCs: ")
    accomplishment= input("Enter an accomplishment: ")
    magical_gear= input("Enter Magical Gear: ")
    political_influence=input("Enter Political Influence: ")
    resource= input("Enter Resource Level: ")
    intel= input("Enter Intel Tier: ")
    research= input("Enter Research: ")
    npc.name = name
    npc.occupation = occupation
    npc.weakness = weakness
    npc.need = need
    npc.desire= desire
    npc.enemy= enemy
    npc.rumor= rumor
    npc.secret= secret
    npc.passion= passion
    npc.redeeming_quality= redeeming_quality
    npc.damning_quality= damning_quality
    npc.happy= happy
    npc.occ_desire=occ_desire
    npc.occ_complication=occ_complication
    npc.pc_opinion=pc_opinion
    npc.accomplishment=accomplishment
    npc.magical_gear=magical_gear
    npc.political_influence=political_influence
    npc.resource=resource
    npc.intel=intel
    npc.research=research


with open(npcs_pickle_file,'wb') as fi:
    # dump your data into the file
    pickle.dump(npcs,fi)

我是菜鸟,因此提供了代码结构,作为到目前为止我在网站上唯一的其他问题的答案。我已将其扩展用于我的目的。

问题是,索引为[1]的NPC已被完美存储,可以根据需要显示并且可以修改。 但是,在定义新的NPC时,我首先得到了新的可索引NPC的IndexError,我被

捕获了
try: #the code for when the NPC has been previously defined
except IndexError:#the code on the last else block,for new indexes

为了检查其余代码是否有效, 并且在我将每个属性定义为

的最后一个else块上出现NameError
self.att=att

现在,我最好的猜测是它与局部变量还是全局变量定义有关,但是我不知道如何解决这两个错误。

非常感谢您阅读全文,对不起。 如果可以,请帮助。

jieqide 回答:先前定义的类方法的名称错误,应存在的索引的IndexError

您的IndexError问题来自取消选择由脚本的先前版本创建的文件。如果该文件包含有价值的数据,请暂时对其进行重命名,一旦脚本正常运行并足够稳定,便是时候编写迁移脚本以恢复旧数据了。否则,就抛弃xD

wrt / NameError,它位于最后一个else块中:您正在尝试在一个npc变量上设置属性,而该变量实际上并未定义-仅在{{1 }}区块:

if

您已经注意到“将代码片段混在一起而不理解它们并不总是有效”,这是一个很好的开始(至少您已经意识到了,所以仍然希望xD),现在这是另一个启发您:“试图理解凌乱的代码很困难”。这就是为什么良好的代码结构很重要的原因。同样,仅(或主要)依赖于其参数的短函数比带有许多条件和代码块的长脚本(其依赖于某个变量(或不定义)大约20多行)更易于理解(和测试!)。

我通常不这样做,但是在这种情况下,您可能会受益于看到结构良好的代码的外观。它远非完美,可以从某些改进中受益(例如,在编辑现有npc时,让用户指定他想要更改的属性,而不是要求他们重新键入所有内容),但是,那是您的工作,不是我的;-)

if npcs[npc_id]:
    npc = npcs[npc_id]
    # way too much code here
else:
    # repeated code here
    # and here's the issue:
    npc.something = something
本文链接:https://www.f2er.com/2765904.html

大家都在问