Python,访问另一个模块(文件)中的dict



我有一个主文件用于我的主代码,一个用于我的类,另一个用于包含dict的价目表。

我想访问dict文件以获取相关价格。它现在看起来的样子(不起作用&忽略缩进(是:


import price_list 

主舱

class Product:
def __init__(self):
self.price_code = "selected_price_code"
self.codes = ["code1", "code2"]

然后是获取价格的函数

def price(self):
prices = []
for i in self.codes:
prices.append(price_list.self.price_code[I])
return sum(prices)

正如您所看到的,访问self.price_code会出错。有什么更好的方法可以做到这一点?我觉得我把事情搞得太复杂了。

现在的错误消息是:[AttributeError:模块"price_list"没有属性"self"]我知道这是因为我做错了,但使用self.input访问另一个文件中的dict有什么更好的方法呢?

如果要访问在__init__中初始化的类的属性,则必须实例化该类。

我不确定我是否足够理解你的想法,但你可以直接将你的常量存储在这样的文件中:

你的foo.py:

price_code = "selected_price_code"
codes = ["code1", "code2"]

然后在你的另一个模块中访问它们,如下所示:

from foo import price_code, codes
# use price_code and codes

如果你更喜欢使用类作为容器,那么可以选择类变量:

foo.py:

Product:
price_code = "selected_price_code"
codes = ["code1", "code2"]

然后访问你的consts如下:

from foo import Product
# Use Product.price_code and Product.codes

让我们在这里下单。根据我得到的文件系统是:

project_folder
--main.py -> here there is Product class
--price_list.py -> here is written the class price_list dict

price_list.py

price_list = { "code1": 5, "code2": 10 }

app.py

# import price_list dict from price_list module
from price_list import price_list
# this class gets the price code as parameter
class Product(price_code):
def __init__(self, price_code):
# initialize price code
self.price_code = price_code
# return the price of the selected code
def get_price(self):
return price_list[self.price_code]
# create a Product instance
product_one = Product("code1")
# get product instance price
product_one_price = product_one.get_price()   # returns 5

我建议你:

  • 制作一个伪代码来明确您想要做什么
  • 研究进口如何运作:文章
  • 研究课堂运作方式:文章

最新更新