7
\$\begingroup\$

I have to create a project in Python 3 for a university exam. The project involves the use of object-oriented programming and the use of multithreading. My project is based on the simulation of booking a hotel room. I then created a Stay class with its instance variables and its methods. For multithreading I tried to implement a competing book, inserting global variables as the number of available rooms by type.

rooms.txt:

Single

Double

Triple

Matrimonial

price_rooms.txt:

Single Yes 46.0

Single No 40.0

Double No 70.5

Double Yes 76.5

Triple No 90.0

Triple Yes 96.0

Matrimonial No 65.0

Matrimonial Yes 71.0

I have doubts about the use of object-oriented programming and especially on multithreading. Can you help me regarding a correct use of this?

from datetime import datetime, date
from threading import Thread
import threading

class Stay:
    '''Classe per la prenotazione di un Stay.'''
    def __init__(self, room_type= '', from_date= '00-00-0000', days= 0, breakfast= '', price= 0.0):
        self._room_type= room_type
        self._from_date= from_date
        self._days= days
        self._breakfast= breakfast
        self._price= price
    def __str__(self):
        return '\nTipology of room: %s\nDate: %s\nNumbers of days: %s\nTotal price: %d\n' % (self._room_type, self._from_date, self._days, self._price)
    def set_room_type (self, room_type):
        while True:
            try:
                try:                
                    rooms= open ('rooms.txt', 'r')
                except IOError:
                    print ('Files for reading the kinds of rooms corrupt or not found\n')
                lista= [] 
                for riga in rooms:                  
                    room = riga.strip()
                    lista.append(room) 
                rooms.close()
                print ('\nSelect the type of room that interests:')
                room=input('')
                if room in lista:
                    room_type= room 
                    self._room_type= room_type
                    break
                elif room.islower(): 
                    raise ValueError
                else:
                    print('Enter a type of room available\n')           
            except ValueError:
                print('Enter the room with only the first letter capitalized\n')


    def get_room_type (self):
        return self._room_type

    def set_from_date (self, from_date):
        date_today = date.today()
        print('Insert the date of arrival:')
        while True:
            data = select_date()
            if data >= date_today:          
                from_date = data
                self._from_date= from_date
                break
            else:
                print('The date is not available')

    def get_from_date (self):
        return self._from_date

    def set_days(self, days):
        while True:
            try:
                print ('How many days you want to stop in our structure?\n')
                ndays=int(input(''))
                if ndays >= 1:
                    days=ndays
                    self._days= days
                    break
                else:
                     ndays == 0
                     print ('Enter a valid number of nights')

            except ValueError:
                print ('Enter a valid character')

    def get_days (self):
        return self._days

    def set_breakfast(self, first_breakfast):
        while True:
            try:
                print ('If you like our breakfast you type Yes, No otherwise')
                first_breakfast= input ('')
                if first_breakfast== 'Si':
                    breakfast= first_breakfast
                    self._breakfast= breakfast
                    break
                elif first_breakfast== 'No':
                    breakfast= first_breakfast
                    self._breakfast= breakfast
                    break
                elif first_breakfast.islower(): 
                    raise ValueError
                else:
                     first_breakfast != 'Yes' or 'No'
                     print('Enter an answer either Yes or No\n')            
            except ValueError:
                print('Enter the answer with only the first letter capitalized\n')

    def get_breakfast(self):
        return self._breakfast

    def set_price(self, price):
        try:
            cal_price= open ('price_rooms.txt', 'r') 
        except IOError:
            print ('Files for searching in prices corrupt or not found')
        for tipo in cal_price:
            riga= tipo.strip() #il metodo strip elimina gli spaziatori da una stringa
            lista= riga.split() #il metodo split spezza una stringa in singole parole
            if lista[0] == self._room_type and lista[1] == self._breakfast: 
                price = float(lista [2])*self._days
                self._price= price
                break
        cal_price.close()

def select_date():
    date_today = date.today() 
    anno = date_today.year 
    while True:
        try:
            print('Enter the day:')
            day = int(input(''))
            print('Enter the mounth:')
            month = int(input(''))
            while True:
                try:
                    print("Enter the year:")
                    year = int(input(''))
                    if anno == year: 
                        break
                    else:
                        if year < anno:
                            print('Enter the correct year')
                        elif year > anno:
                            print("You can not select a year other than the current one")
                except ValueError:
                    print('Invalid character')
            data = date(year, month, day)  
            break
        except ValueError:
            print("Invalid date . Enter the date correctly.")
    return data

def prenotazione (sema, op):
    sema.acquire() 
    op.set_room_type('room_type')
    op.set_from_date('from_date')
    op.set_days('days')
    op.set_breakfast('breakfast')
    op.set_price('price')
    print(op)
    global Single, Double, Triple, Matrimonial
    if op._room_type == 'Single' and Single > 0:
        Single = Single -1
    elif op._room_type == 'Double' and Double > 0:
        Double = Double -1
    elif op._room_type == 'Triple' and Triple > 0:
        Triple = Triple -1
    elif op._room_type == 'Matrimonial' and Matrimonial > 0:
        Matrimonial = Matrimonial -1
    else:
        print ('We are sorry , the type of room selected by you is not available , try to select another type')

    sema.release() 

print("Welcome to the reservation service rooms of our structure\nThe types of rooms available are the following:\n")

try:
    roomsdisp = open('rooms.txt','r')
except IOError:
    print ('Files for reading rooms corrupt or not found')
lista = []
for riga in roomsdisp:
    rooms = riga.strip() 
    lista.append(rooms) 
    print (rooms)
roomsdisp.close()   

Single= 1 
Double= 2
Triple= 1
Matrimonial= 1
reservation= Stay () 
sema = threading.Semaphore (1)
t1 = Thread(target = prenotazione, args = (sema, reservation,)) 
reservation2 = Stay()
t2 = Thread(target = prenotazione, args = (sema, reservation2,))
reservation3 = Stay()
t3 = Thread(target =prenotazione, args = (sema,reservation3,))

t1.start()
t2.start()
t3.start()
\$\endgroup\$
  • 4
    \$\begingroup\$ Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. \$\endgroup\$ – Vogel612 Jun 21 '16 at 14:03
4
\$\begingroup\$

== instead of = "bug"

I saw this line in your code:

ndays == 0

In Python assignment is done with a singe =, using double == you are asking Python if the objects are equal and discarding the result of such comparison, there is no crash / unexpected behaviour here because ndays=int(input('')) overwrites ndays shortly thereafter anyway (so setting it to 0 would have been useless too).

I suggest removing such a weird "do nothing" line from your code to avoid confusing the readers (and yourself of the future).

Critical UI flaw

You asked for yes but checked for Si (italian word meaning yes).

The user will be unable to proceed in this branch because of this flaw:

            print ('If you like our breakfast you type Yes, No otherwise')
            first_breakfast= input ('')
            if first_breakfast== 'Si':
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I thank you for the answer. I will correct mistakes , can you tell me how to improve the reservation through multithreading ? \$\endgroup\$ – Peter Jun 21 '16 at 8:32
  • \$\begingroup\$ @Peter I am sorry but I cannot help you on multithreading, try asking a follow-up question more focused on that issue. \$\endgroup\$ – Caridorc Jun 23 '16 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.