这是我作为程序员的第一个月,所以我正在创建一个电影预订网站的副本。我在我的main.py
文件中写了一些代码:
def main():
current_income=0
print('---->Enter the number of row in Cinemahall :- ')
while True:
try:
row=int(input())
break
except:
print('-->Something went wrong!! Please enter the valid row in cinemahall. The value must be integer type :')
print("---->Enter the number of column in Cinemahall :- ")
while True:
try:
col=int(input())
break
except:
print('-->Something went wrong!! Please enter the valid column in cinemahall. The value must be integer type :')
while True:
import options_movies
options_movies.options()
break
if __name__=='__main__':
main()
现在我有另一个文件options.py
:
def options():
while True:
print('1. show the seats')
print('2. buy a ticket')
print('3. statistics')
print('4. show booked ticked user info')
print('0. exit')
print('--> Please select one option from 1,2,3,4,0 ')
##try:
n=int(input())
if n==1:
from main import main
import show_seats
show_seats.show_the_seats(main.row,main.col)
elif n==2:
import buy_ticket
buy_ticket.buy_a_ticket()
elif n==3:
import statistics
statistics.statistics()
elif n==4:
import user_info
user_info.booked_ticket_user_info()
elif n==0:
print('Thank you for using BOOK MY SHOW,We hope you will enjoy the show...... Please visit again!!')
break
##assert n>=0 and n<=4
## except:
## print('Something went wrong!!!! Please enter the valid option from 1,2,3,4,0')
现在,当我试图从main.py文件中使用show_seats.show_the_seats()中的row和col值时,我得到了这个错误
File "C:UsersROHIT KUMAR VERMAOneDriveDocumentsBook My Show Projectmain.py", line 23, in <module>
main()
File "C:UsersROHIT KUMAR VERMAOneDriveDocumentsBook My Show Projectmain.py", line 20, in main
options_movies.options()
File "C:UsersROHIT KUMAR VERMAOneDriveDocumentsBook My Show Projectoptions_movies.py", line 16, in options
show_seats.show_the_seats(main.row,main.col)
AttributeError: 'function' object has no attribute 'row'
在函数内部创建的变量只能在该函数内部使用。您需要创建全局变量:
my_variable = "awesome"
def myfunc():
print("Python is " + my_variable)
myfunc()
现在,您可以将变量导入到您需要的文件中:
from filename import variable
参:
- https://www.w3schools.com/python/python_variables_global.asp
- https://www.kite.com/python/answers/how-to-import-variables-from-another-file-in-python