1

嗨,我正在 python 上制作一个程序,我在向我的程序添加全局变量时遇到了麻烦,所以我只想发布我的代码并向你展示我是如何尝试这样做的。

所以这是我的课:

import globalvariables

class Bus :  

def __init__(self, Number, Capacity, Destination, Seats):
    self.Bus_Number = Number
    self.Bus_Capacity = Capacity
    self.Bus_Destination = Destination
    self.Seats_taken = Seats

def Book(self):
    self.Seats_taken = Seats + 1

def ShowBus(self):
    return (str(self.Bus_Number) + ", " + str(self.Bus_Capacity) + ", " + str(self.Bus_Destination) + ", " + str(self.Seats_taken))

这是我的全局变量模块

Seats = 0

这就是我要运行的:

import Transport
import globalvariables

Big_Red = Transport.Bus(1, 50, "NYC", 0)
Big_Red.Book()

print(Big_Red.ShowBus())

我收到此错误:

Traceback (most recent call last):
  File "D:\Python\Assignment 3\Tester.py", line 5, in <module>
    Big_Red.Book()
  File "D:\Python\Assignment 3\Transport.py", line 14, in Book
    self.Seats_taken = Seats + 1
NameError: global name 'Seats' is not defined
4

3 回答 3

1

该变量Seats__init__函数的局部变量,不能在它之外访问。

所以,

self.Seats_taken = Seats + 1

应该 :

self.Seats_taken =  self.Seats_taken + 1

或者 :

self.Seats_taken += 1 

而不是在类中使用全局变量,您应该使用类属性:

class Bus :
    seats = 50  #shared across all instances
    def __init__(self):
        #code 
    def Book(self):
        self.Seats_taken = self.seats + 1
于 2013-07-08T22:51:13.733 回答
1

应避免使用全局变量。如果您仍然希望它是:

def Book(self):
    self.Seats_taken = globalvariables.Seats + 1
于 2013-07-08T23:07:28.617 回答
0

当您 时import globalvariables,您可以访问由模块名称限定的名称:globalvariables.Seats. 要导入Seats另一个模块的命名空间,请使用from globalvariables import Seats. (在绝望的情况下,您可以从模块中导入所有名称:from globalvariables import *,但通常您不希望这样做。)

当你定义一个函数时,它有自己的本地命名空间。它包括所有函数的参数。

Seats = 100

def foo(Seats):
  # returns the value of variable named Seats
  # defined within "def foo", *not* defined by "Seats = 100"
  return Seats

print foo(200) # prints 200
print foo() # fails because Seats are not set

要初始化函数参数,请使用默认值:

def foo(seats=0):

print foo() # prints 0
print foo(55) # prints 55  

此外,全局变量是邪恶的。全局常量很好。

您想使用全局变量来跟踪占用的座位。如果你将它封装到一个只允许合理访问、不允许任意设置值、如果需要记录访问等的类中,你会好得多:

class SeatsDispenser(object):
  def __init__(self, initial_count):
    self.count = initial_count

  def allocate(self, number_of_seats):
    self.count -= number_of_seats
    if self.count < 0:
      raise ValueError("Overcommitted!")

  def seats_left(self):
    return self.number_of_seats

用相同的标题案例命名变量、类、常量和函数是不切实际的。通常变量是 lower_case,函数是 lowerCamelCase,类是 TitleCamelCase,常量是 ALL_CAPS。

一段合理的代码如下所示:

import constants # modules are usually lower case
import transport

def Bus(object):
  def __init__(self, number, capacity, seats=constants.SEATS):
    self.number = number
    self.capacity = capacity
    self.seats = seats

big_red = Bus(constants.NYC_BUS_NUMBER, 50, 25)
default_blue = Bus(1, 20) # seats not passed, the default value is used

seats_dispenser = SeatsDispenser(100)
seats_dispenser.allocate(big_red.count)
seats_dispenser.allocate(default_blue.count)
print seats_dispenser.seats.left()
于 2013-07-08T23:12:28.420 回答