【问题标题】:Class does not seem to be Global in python类在python中似乎不是全局的
【发布时间】:2023-04-04 04:06:01
【问题描述】:

我设置了一个类,它在一个 if 语句中接受并打印出变量。

class npc: #class for creating mooks
    def __init__(self, name):
        self.name = name
    def npc_iq (self,iq):
        self.iq = []
    def npc_pp (self,pp):
        self.pp = []
    def npc_melee (self, melee):
        self.melee = []
    def npc_ct (self, ct):
        self.ct = []

在这个 if 语句中可以正常工作

if menu_option == 1:
    print "Choose melees for npc"
    init_bonus = random.randint(0,2)
    char_PP = random.randint(7,15)
    char_iq = random.randint(7,15)
    npc_Melees = int(raw_input(prompt))
    combat_time = math.floor((round_attacks - init_bonus - math.floor(char_PP/2) - math.floor(char_iq/2)) / npc_Melees)
    #function for calculating sequence number
    print "combat time is"
    print combat_time
    mook = "mook%s" % counter # adds different mook names to program
    mook = npc(mook) 
    mook.iq = (char_iq)
    mook.pp = (char_PP)
    mook.melee = (npc_Melees)
    mook.ct = (combat_time)
    counter += 1

但是在这个语句中它会打印出类中的名字而不是ct。

elif menu_option ==4:
    print "Printing out all mooks"
    print
    printcount = counter -1
    while printcount != 0:
        mookprint = "mook%s" % printcount
        mookprint = npc(mookprint)
        print mookprint.name
        print mookprint.ct 
        print
        printcount -= 1

【问题讨论】:

  • 如果它打印name,那么mookprint 不是None。那么你确定ct 确实有值吗?
  • ct 的值在第一个 if 循环中打印得很好。运行另一行时出现 AttributeError: npc instance has no attribute 'ct' 的错误。
  • 您似乎对课程的运作方式有些误解。例如,您打印 moodprint.ct 时从未设置对象的 ct 成员。

标签:
python
class
global
local