如何将文件中的所有项设置为字典中的内容

huangapple go评论62阅读模式
英文:

How to set all items from a file into a dict

问题

self.items = {name: item for name, item in item_file.__dict__.items() if not name.startswith("__") and isinstance(item, item_file.items)}
英文:

I have a File to define items

# Items.py

class items:
    def __init__(self, name, can_sell):
        self.name = name
        self.can_sell = can_sell

item_1 = item('sword', True) #You can sell this item
item_2 = item('shield', False) #You cant sell this item

and a file to sell items

# Sell.py

import Items as item_file

class sell:
    def __init__(self):
        self.items = #all items in item.py (dictionary)
        self.inv = #all items in item.py (dictionary)

    def sell_function(self):
        print("SELL 'item_name' or EXIT")        
        player_input = input(">  ")
        if player_input == "EXIT":
            exit()
        elif "SELL" in player_input:
            selling_item = player_input.split(' ')][-1]
            if selling_item in self.inv:
                if self.inv[selling_item]['can_sell'] is True:
                    self.inv.pop(selling_item)
            else:
                print("You dont have such item")
                exit()

How can I code the following part?
self.items = #all items in item.py (dictionary)

I have tried
self.items = {item for item in item_file}
but it returns
TypeError: 'module' object is not iterable

I know the for line in item_file method, but it would get the class lines too.
How can I just get the items in the file?

答案1

得分: 1

似乎你可能开始构建程序的某种奇怪结构。你可能要考虑一下是否将类用于像卖东西这样的操作是一个逻辑上的方法。它更像是一个动作(方法),而不是一个对象。

无论如何,你可以使用类属性来存储该类创建的所有新对象:

class Item:
    all_items = []
    def __init__(self, name, can_sell):
        self.name = name
        self.can_sell = can_sell
        self.all_items.append(self)

item_1 = Item('sword', True) #你可以出售这个物品
item_2 = Item('shield', False) #你不能出售这个物品

print([i.name for i in Item.all_items])

class Sell:
    def __init__(self):
        self.items = Item.all_items

a = Sell()

print([i.name for i in a.items])

如你所见,变量all_items是在__init__函数外部定义的,因此它属于类本身而不是实例。你可以从类访问它,而不是从其实例访问,因此使用Item.all_items

请注意,当你使用变量名命名类时,这会让人感到困惑。你必须使用UpperCamelCase来命名类

再次强调,Item类包含所有物品的逻辑是什么?我不确定。也许你想要为包含物品并跟踪所有物品的库创建某种类,然后也许你可以从一个库向另一个库出售物品之类的事情。我认为用Python对象来表示对象的真实概念可能更合理,这样在思考程序中的过程和数据时会更容易。

英文:

It seems like you might be starting to construct some weird structure of your program. You might want to consider if it is a logical approach to have a class for some action like selling. It seems more like an action(so method) one would do, not an object.

In any case, you can use class attribute to store all new objects of that class created:

class Item:
    all_items = []
    def __init__(self, name, can_sell):
        self.name = name
        self.can_sell = can_sell
        self.all_items.append(self)

item_1 = Item('sword', True) #You can sell this item
item_2 = Item('shield', False) #You cant sell this item

print([i.name for i in Item.all_items])

class Sell:
    def __init__(self):
        self.items = Item.all_items

a = Sell()

print([i.name for i in a.items])

As you can see that variable all_items is defined outside __init__ function, so it belongs to the class itself and not instances. You would access it form the class and not its instances as well so Item.all_items

Note that it is confusing when you call classes with variable name convention. You have to name classes in UpperCamelCase.

Once again, what's the logic of Item class containing all the items?.. I am not sure. Maybe you might want to have some sort of a class for inventory that would contain items and it would track all items. And then maybe you could sell items from one inventory to another or something like that. I think it might be logical to represent real concepts of objects with Python objects so it is easier to think about the processes and data in your program.

huangapple
  • 本文由 发表于 2023年7月17日 18:26:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定