【问题标题】:Add all class variables to a list将所有类变量添加到列表
【发布时间】:2021-12-27 00:01:15
【问题描述】:

我想将所有使用 items 类的变量添加到列表中,而无需在每次创建新项目时手动将每个项目添加到列表中。 例如itemsList = [flower, wood, iron, sticks]

flower = items(red, "flower", "0001",xpositions[0] ,ypositions[0])
wood = items(brown, "wood", "0002",xpositions[1] ,ypositions[1])
iron = items(iron, "iron", "0003",xpositions[2] ,ypositions[2])
sticks = items(brown, "sticks", "0004",xpositions[3] ,ypositions[3])

itemsList = []

类的代码

class items:
    def __init__(self, colour, name, ID, xpos, ypos):
        self.width = 20
        self.height = 20
        self.colour = colour
        self.name = name
        self.ID = ID
        self.xpos = xpos
        self.ypos = ypos

【问题讨论】:

标签: python list class


【解决方案1】:

考虑使用字典而不是松散变量。

my_items = {}
...
my_items["flower"] = items(red, "flower", "0001", xpositions[0], ypositions[0])
my_items["wood"] = items(brown, "wood", "0002", xpositions[1], ypositions[1])
my_items["iron"] = items(iron, "iron", "0003", xpositions[2], ypositions[2])
my_items["sticks"] = items(brown, "sticks", "0004", xpositions[3], ypositions[3])

以后如果您想使用它们中的任何一个,您可以通过my_items 字典中的名称访问它们,例如my_items["flower"]

【讨论】:

    【解决方案2】:

    您可以创建一个列表类变量并将self 附加到__init__ 中的类变量。您可以发布您班级的代码吗?我也许可以演示一下。

    编辑-刚刚测试了这个,我相信这应该是你想要的,虽然我有点不清楚: 即

    class Item:
        list = []
        def __init__(self):
            Item.list.append(self)
    
    a = Item()
    b = Item()
    print(Item.list)
    

    然后您可以直接通过类(通过Item.list)或在任何项目中访问它,但如果您进行更改,事情会变得很奇怪,因为它在您更改后表现得像一个实例属性,所以我建议不要这样做。

    我看到你说你只想要一个名字列表的评论。我不确定您是否想要相同或物品,但这里是列表中的名称:

    class items:
        items_list = []
        def __init__(self, colour, name, ID, xpos, ypos):
            self.width = 20
            self.height = 20
            self.colour = colour
            self.name = name
            self.ID = ID
            self.xpos = xpos
            self.ypos = ypos
            Item.item_list.append(self.name)
    

    更灵活

    class items:
        items_list = []
        def __init__(self, colour, name, ID, xpos, ypos):
            self.width = 20
            self.height = 20
            self.colour = colour
            self.name = name
            self.ID = ID
            self.xpos = xpos
            self.ypos = ypos
            Item.item_list.append(self)
    
        def __str__(self):
            return f'{self.name}'
    

    额外的 str 将做同样的事情,但实际上存储项目并打印出项目名称列表。

    但是你需要澄清你是想要项目列表还是项目名称列表。这些是不同的东西。

    【讨论】:

    • 请不要在您的帖子中添加评论。我为您删除了它,但如果您愿意,您可以在 the relevant answer 上发表评论。
    • 我不确定您所说的“在帖子中添加评论”是什么意思,但由于本网站的规定,无论如何我都不能对帖子发表评论。
    • 啊,抱歉,您还不能comment everywhere。我的意思是,你写了 “我看到其他人......回答了同样的事情......尽管他们由于某种原因被否决了。” Stack Overflow 是一个参考网站,所以东西像这样,与 your 答案无关的是noise,应该被删除。顺便说一句,你可以看看the revision history 看看我改变了什么。
    • 好吧,我想给他们一些荣誉,因为我忘记了类属性的确切语法,但我明白你的意思。
    【解决方案3】:

    您可以使用 locals() 或 globals() 从当前作用域获取各个变量名称。如果您真正想要的是存储在变量中的实例列表,则可以使用类似的方法。

    class items:
        ...
            
        def variables(scope=globals()):
            return [name for name,i in scope.items() if isinstance(i,items)]
    
        def instances(scope=globals()):
            return [value for value in scope.values() if isinstance(value,items)]
    

    全球范围:

    gFlower = items(red, "flower", "0001",xpositions[0] ,ypositions[0])
    gWood   = items(brown, "wood", "0002",xpositions[1] ,ypositions[1])
    gIron   = items(iron, "iron", "0003",xpositions[2] ,ypositions[2])
    gSticks = items(brown, "sticks", "0004",xpositions[3] ,ypositions[3])
    
    print(items.variables())
    ['gFlower', 'gWood', 'gIron', 'gSticks']   # variable names
    
    print([i.name for i in items.instances()])
    ['flower', 'wood', 'iron', 'sticks']       # self.name of each instance
    

    本地范围(例如在函数内部):

    def myFunction():
        myflower = items(red, "flower", "0001",xpositions[0] ,ypositions[0])
        mywood   = items(brown, "wood", "0002",xpositions[1] ,ypositions[1])
        myiron   = items(iron, "iron", "0003",xpositions[2] ,ypositions[2])
        mysticks = items(brown, "sticks", "0004",xpositions[3] ,ypositions[3])
        print(items.variables(locals()))
    
    myFunction()
    ['myflower', 'mywood', 'myiron', 'mysticks']
    

    【讨论】:

      【解决方案4】:

      itemsList.append 添加到项目类的__init__ 函数中。

      class Item:
          itemsList = []
      
          def __init__(self, *args):
              self.data = [arg for arg in args]
              
              # This line here is what you want
              Item.itemsList.append(self)
      

      【讨论】:

        【解决方案5】:

        这个问题有点不清楚,但你可以试试这样的

        itemsList = []
        itemsList.append(items(red, "flower", "0001",xpositions[0] ,ypositions[0]))
        itemsList.append(items(brown, "wood", "0002",xpositions[1] ,ypositions[1]))
        itemsList.append(items(iron, "iron", "0003",xpositions[2] ,ypositions[2]))
        itemsList.append(items(brown, "sticks", "0004",xpositions[3] ,ypositions[3]))
        

        但如果您的意思是它会自动自动添加到列表中,那么这是不可能的

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-07
          • 1970-01-01
          • 1970-01-01
          • 2019-07-01
          • 2014-08-13
          • 1970-01-01
          • 2021-12-13
          • 2023-03-31
          相关资源
          最近更新 更多