【问题标题】: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


【解决方案1】:

为什么 mookprint 知道 ct 应该是什么值? npc 的构造函数初始化一个新的 npc 实例,名称作为参数给出,但 ct 为空。

当您在菜单选项 1 中创建 NPC 时,您不会创建 npc 的全局实例。如果要引用以前创建的 npc 实例,则需要找到某种存储方式。字典可能是您的一个很好的解决方案。字典是保存键和值之间映射的对象。如果您知道密钥,则可以找到关联的值。在这种情况下,您可以将 name 设为键,将值设为 npc 实例。

例如。

npcsDict = dict()

if menu_option == 1:

   # code for intialising a new instance of npc
   ...
   # most, if not all of the initialisation code should be moved to the 
   # __init__ method for npc

   # now store the newly created mook
   npcsDict[mook.name] = mook

elif menu_option == 4:

    print "Printing out all mooks"
    print
    for mookName in npcsDict:
        print npcsDict[mookName].name
        print npcsDict[mookName].ct
        print

【讨论】:

  • 谢谢,这看起来就像我最初尝试做的那样。
【解决方案2】:

我真的不明白你的问题。

您的工作示例:

mook = npc(mook) 
mook.iq = (char_iq)
mook.pp = (char_PP)
mook.melee = (npc_Melees)
mook.ct = (combat_time)

mook.ct 是 (combat_time) 的值

你失败的例子:

mookprint = npc(mookprint)
print mookprint.name
print mookprint.ct 

mookprint.ct 的值什么都不是,因为它从未设置过。

【讨论】:

  • 完美!我完全没有意识到我实际上没有从课堂上得到任何信息。
  • 所以,这就是问题所在?那么请将我的答案标记为解决方案;)还是我完全错了?
  • 每个人都在这方面提供了很多帮助。感谢您对菜鸟的耐心。
  • 没有人是菜鸟,只是需要更多经验 :) 您在设计方面需要更多帮助吗?
【解决方案3】:

只有在 if 没有的情况下才会执行 elif,因此如果 elif 块运行,则永远不会设置 ct

【讨论】:

    【解决方案4】:

    我认为您不了解四行代码的工作原理:

    mookprint = "mook%s" % printcount
    mookprint = npc(mookprint)
    print mookprint.name
    print mookprint.ct 
    

    每次运行这段代码时,都会发生以下事情:

    1. 您将"mook" 形式的字符串分配给变量mookprint
    2. 您正在创建一个新的instance,它是npc class。您应该注意,您创建的所有实例都将彼此分开。这个新实例将有一个属性,其名称之前保存在变量mookprint 中,而这个npc 实例将分配给mookprint
    3. 您正在打印您在上一步中创建的npc 类的实例name 属性。这是有效的,因为在创建此实例时,您的类的 __init__ 方法被调用,参数 name 设置为“mook1”或当时存储在 mookprint 中的任何内容。
    4. 您正在打印刚刚创建的npc 类的instancect 属性。由于您从未将 ct 属性设置为任何内容,因此这不会按您的预期工作。

    如果您想计算npc 类的实例数,您需要创建一个class attribute。这是一个变量,其值在类的所有实例中是通用的。为此,您需要修改您的类定义,以便在每次创建该类的新实例时向该属性添加一个项目。它看起来像这样:

    class npc: #class for creating mooks
        ct = []
        def __init__(self, name):
            self.name = name
            self.ct.append(name)
    
        def get_ct(self):
            return len(self.ct)
    

    通过上述,变量ct 将是一个列表,该列表对npc 的所有实例都是通用的,并且每次创建新的npc 时都会增长。然后get_ct方法会计算这个列表的长度。

    然后你需要修改我提到的四行看起来像:

    mookprint = "mook%s" % printcount
    mookprint = npc(mookprint)
    print mookprint.name
    print mookprint.get_ct()
    

    我认为上面的代码显示了如何更改您的代码以使其更符合您的预期。但是,应该注意的是,您很少希望创建每个实例都依赖于其他实例信息的类。执行 Dunes 建议的操作通常是更好的设计,将实例存储在字典或其他数据结构中,并以这种方式跟踪它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多