Python 类在函数中被视为变量

Python 类在函数中被视为变量,python,python-3.x,class,Python,Python 3.x,Class,我正在用Python编写一段代码,为PC建筑车间创建一个订单系统,并有一个“order”类,其中包含一个打印订单的方法。当我在我的一个函数(下单)中引用这个(创建订单)时,它工作得很好。例如: order1 = order(1,'Luke','p5','16gb','1tb','19in','midi','4usb') 但是,当我在“main”函数中引用它时,在运行代码时会出现以下错误: 文件“program.py”,第103行,在main中 顺序1=顺序(1、'Luke'、'p5'、'16g

我正在用Python编写一段代码,为PC建筑车间创建一个订单系统,并有一个“order”类,其中包含一个打印订单的方法。当我在我的一个函数(下单)中引用这个(创建订单)时,它工作得很好。例如:

order1 = order(1,'Luke','p5','16gb','1tb','19in','midi','4usb')
但是,当我在“main”函数中引用它时,在运行代码时会出现以下错误:

文件“program.py”,第103行,在main中
顺序1=顺序(1、'Luke'、'p5'、'16gb'、'1tb'、'19in'、'midi'、'4usb')
UnboundLocalError:赋值前引用的局部变量“order”
这对我来说毫无意义,因为它在我的其他功能中工作得非常好。整个代码打印在下面。您可以在“main”函数中看到在函数的第一行和第二行中首先调用错误的那一行,之后如果输入文本“test”,它也会返回错误,没有明显的原因。我正在MacOSX上使用Python 3.6.3

#!/usr/bin/env python3

class order(object):
    def __init__(self, orderNo, customer, processor, ram, storage, screen, case, usb):
        self.orderNo = orderNo
        self.customer = customer
        self.processor = processor
        self.ram = ram
        self.storage = storage
        self.screen = screen
        self.case = case
        self.usb = usb

    def stockCost(self):
        global componentCosts
        return componentCosts[self.processor] + componentCosts[self.ram] + componentCosts[self.storage] + componentCosts[self.screen]+ componentCosts[self.case]+ componentCosts[self.usb]

    def salePrice(self):
        return self.stockCost() * 1.2

    def print_order(self):
        """Prints the data of an order in a viewable way for the vendor"""
        return 'Order number: {}, for customer: {}.\n'.format(self.orderNo, self.customer) \
        + '{} processor.\n'.format(self.processor) \
        + '{} of ram.\n'.format(self.ram.upper()) \
        + '{} of storage.\n'.format(self.storage.upper()) \
        + '{} screen.\n'.format(self.screen) \
        + '{}{} case.\n'.format(self.case.lower()[0].upper(), self.case.lower()[1:])\
        + '{} {} ports.\n'.format(self.usb[0], self.usb[1:].upper()) \
        + 'Your chosen build will cost ${:0.2f}.\n'.format(self.salePrice())

    def user_print_order(self):
        """Prints the data of an order in a viewable way for the customer"""
        return '{}, your order number is {}.\n'.format(self.customer, self.orderNo) \
        + 'You have chosen a {} processor.\n'.format(self.processor) \
        + 'You have chosen {} of ram.\n'.format(self.ram.upper()) \
        + 'You have chosen to have {} of storage.\n'.format(self.storage.upper()) \
        + 'You have chosen a {} screen.\n'.format(self.screen) \
        + 'You have chosen a {}{} case.\n'.format(self.case.lower()[0].upper(), self.case.lower()[1:])\
        + 'You have chosen to have {} {} ports.\n'.format(self.usb[0], self.usb[1:].upper()) \
        + 'Your chosen build will cost ${:0.2f}.\n'.format(self.salePrice())


def place_order():
    global componentList
    global stock
    global orders
    orderOK = True
    componentChoices = {}
    print ('Please choose your components, These are your options:\n(please enter the component as they appear on the component list)\n' + componentList)
    name = input('Please enter your name: ')
    componentChoices['processor'] = input('Please enter what processor you would like: ')
    componentChoices['ram'] = input('Please enter how much ram you would like: ')
    componentChoices['storage'] = input('Please enter how much storage you would like: ')
    componentChoices['screen'] = input('Please enter how big a screen you would like: ')
    componentChoices['case'] = input('Please enter what size case you would like: ')
    componentChoices['usb'] = input('Please enter whether you would like 4 USB ports or 2 (enter 4USB or 2USB): ')
    for part in componentChoices:
        choice = componentChoices[part].lower()
        if stock[choice] < 1:
            print ('Your choice of {} is out of stock, please choose a different option.\n'.format(part) + componentList)
            componentChoice[part] = input('Enter your new choice of {}.'.format(part))
            if stock[componentChoices[part]] < 1:
                print ('Your choice of {} is also out of stock, your order has thus failed to go through. Please try again later.')
                orderOK = False
                return None
        else: stock[componentChoices[part].lower()] -= 1

    toBeReturned = order(len(orders)+1, name, componentChoices['processor'], componentChoices['ram'], componentChoices['storage'], componentChoices['screen'], componentChoices['case'], componentChoices['usb'])
    print (toBeReturned.user_print_order())
    query = input('Is this information correct? Enter "Y" or "N".')
    while True:
        if query.lower() == 'y':
            break
        if query.lower == 'n':
            print('Your order has not been placed, please re-place the order')
            return None

    return toBeReturned


componentList = 'Processor: p3, p5 or p7\nRAM: 16GB or 32GB\nStorage: 1TB or 2TB\nScreen: 19in or 23in\nCase Size: Mini or Midi\nNo of Ports: 2USB or 4USB'

componentCosts = {
'p3': 100, 'p5': 120, 'p7': 200, '16gb': 75, '32gb': 150,
'1tb': 50, '2tb': 100, '19in': 65, '23in': 120, 'mini': 40,
'midi': 70, '2usb': 10, '4usb': 20
}
stock = {
'p3': 100, 'p5': 100, 'p7': 100, '16gb': 100, '32gb': 100,
'1tb': 100, '2tb': 100, '19in': 100, '23in': 100, 'mini': 100,
'midi': 100, '2usb': 100, '4usb': 100
}

orders = {}

#~ order1 = order(1,'Luke','p5','16gb','1tb','19in','midi','4usb')
#~ print (order1.print_order())

def main():
    order1 = order(1,'Luke','p5','16gb','1tb','19in','midi','4usb')
    print (order1.print_order())
    global componentList
    global stock
    global orders
    while True:
        print ('\nEnter "make" to place an order, "view" to view previous orders, "stock" to view the stock levels, and "quit" to quit the program. Quitting the program will lose records of previous orders, please back them up by copying the output from entering "view".')
        command = input().lower()
        while True:
            if command == 'quit':
                return False
            if command == 'view':
                for order in orders:
                    print (orders[order].print_order()+'\n')
                break
            if command == 'make':
                #~ globals()["order" + str(len(orders)+1)] = place_order()
                order1 = order()
                if globals()["order" + str(len(orders)+1)] == None:
                    break
                else:
                    orders[len(orders)+1] = globals()["order" + str(len(orders)+1)]
                    break
            if command == 'stock':
                for i in stock:
                    print(i + ': ' + str(stock[i]))
            if command == 'test':
                for i in range(10):
                    globals()["order" + str(i)] = order(i,'Luke','p5','16gb','1tb','19in','midi','4usb')
                    orders[len(orders)+1] = globals()["order" + str(i)]
            else:
                print('Invalid option entered please try again')
                break

if __name__ == "__main__":
    main()
#/usr/bin/env蟒蛇3
类顺序(对象):
def _;初始化(自身、订单号、客户、处理器、ram、存储器、屏幕、机箱、usb):
self.orderNo=orderNo
self.customer=客户
self.processor=处理器
self.ram=ram
self.storage=存储
self.screen=屏幕
self.case=case
self.usb=usb
def库存成本(自身):
全球组成部分成本
返回组件成本[self.processor]+组件成本[self.ram]+组件成本[self.storage]+组件成本[self.screen]+组件成本[self.case]+组件成本[self.usb]
def销售价格(自我):
返回self.stockCost()*1.2
def打印顺序(自):
“”“以可供供应商查看的方式打印订单数据”“”
返回“订单号:{},对于客户:{}。\n”。格式(self.orderNo,self.customer)\
+{}处理器。\n.格式(self.processor)\
+ram的'{}.\n'.格式(self.ram.upper())\
+“{}”存储。\n.格式(self.storage.upper())\
+{}屏幕。\n.格式(self.screen)\
+{}{}case.\n.格式(self.case.lower()[0].upper(),self.case.lower()[1:]\
+“{}{}端口。\n.”格式(self.usb[0],self.usb[1:][.upper())\
+'您选择的生成将花费${:0.2f}。\n'。格式(self.salePrice())
def用户打印订单(自我):
“”“以可查看的方式为客户打印订单数据”“”
返回{},您的订单号为{}。\n.格式(self.customer,self.orderNo)\
+'您选择了一个{}处理器。\n'。格式(self.processor)\
+'您选择了{}个ram。\n'。格式(self.ram.upper())\
+'您已选择有{}个存储。\n'。格式(self.storage.upper())\
+'您选择了一个{}屏幕。\n'。格式(self.screen)\
+'您选择了一个{}{}大小写。\n'。格式(self.case.lower()[0]。upper(),self.case.lower()[1:])\
+'您已选择有{}{}个端口。\n'。格式(self.usb[0],self.usb[1:][.upper())\
+'您选择的生成将花费${:0.2f}。\n'。格式(self.salePrice())
def下订单():
全局组件列表
全球股票
全球订单
orderOK=True
componentChoices={}
打印('请选择您的组件,这些是您的选项:\n(请输入组件列表中显示的组件)\n'+组件列表)
name=input('请输入您的姓名:')
componentChoices['processor']=input('请输入您想要的处理器:')
componentChoices['ram']=input('请输入您想要的ram量:')
componentChoices['storage']=input('请输入所需的存储空间:')
componentChoices['screen']=input('请输入您想要的屏幕大小:')
componentChoices['case']=input('请输入您想要的大小:')
componentChoices['usb']=input('请输入您想要4个usb端口还是2个(输入4USB或2USB):')
对于部件中的部件选择:
choice=componentChoices[part].lower()
如果股票[选择]<1:
打印('您选择的{}已售完,请选择其他选项。\n'。格式(部分)+组件列表)
componentChoice[part]=input('输入新的{}.'。格式(part))
如果库存[componentChoices[part]]<1:
print('您选择的{}也缺货,因此您的订单无法通过。请稍后再试。')
orderOK=False
一无所获
其他:库存[componentChoices[part].lower()]-=1
toBeReturned=order(len(orders)+1、名称、组件选项['processor']、组件选项['ram']、组件选项['storage']、组件选项['screen']、组件选项['case']、组件选项['usb'])
打印(toBeReturned.user\u print\u order())
查询=输入('此信息正确吗?输入“Y”或“N”。)
尽管如此:
如果query.lower()
打破
如果query.lower='n':
打印('您的订单尚未下单,请重新下单')
一无所获
返航
componentList='处理器:p3、p5或p7\nRAM:16GB或32GB\n存储:1TB或2TB\n屏幕:19in或23in\n机箱大小:Mini或Midi\n无端口:2USB或4USB'
组成部分成本={
'p3':100,'p5':120,'p7':200,'16gb':75,'32gb':150,
'1tb':50,'2tb':100,'19in':65,'23in':120,'迷你':40,
“midi”:70,“2usb”:10,“4usb”:20
}
股票={
'p3':100,'p5':100,'p7':100,'16gb':100,'32gb':100,
'1tb':100,'2tb':100,'19in':100,'23in':100,'mini':100,
“midi”:100,“2usb”:100,“4usb”:100
}
订单={}
#~order1=顺序(1、'Luke'、'p5'、'16gb'、'1tb'、'19in'、'midi'、'4usb')
#~print(order1.print_order())
def main():
顺序1=顺序(1、'Luke'、'p5'、'16gb'、'1tb'、'19in'、'midi'、'4usb')
打印(订单1.打印订单())
全局组件列表
全球股票
全球订单
尽管如此:
打印('\n输入“make”以下订单,“view”以查看以前的订单,“stock”以查看
for order in orders:
    ...