You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

车辆租赁程序开发:CSV写入、租赁活跃判定及Aluguer类优化问题

Vehicle Rental Program: Fixes & Enhancements

Let's work through your questions and refine your Aluguer class to meet all your requirements.

1. Can the inicio property correctly track rental start time?

Short answer: No, your current implementation is broken. Here's why:

  • You defined a global now = time.time() when the module loads—this value is fixed at import time, not when the Aluguer object is created.
  • Your inicio property overwrites self.__inicio with this fixed now every time you access it. That means every call to aluguer.inicio will reset the start time to when the module was first loaded, not when the rental actually started.

Fix for inicio:

We need to set the start time once when the rental is created, then let the property only return it (no modification). Here's the corrected approach (auto-setting start time when the rental is initialized, the most common use case):

import time

class Aluguer:
    def __init__(self, nickname, nome, preco_base):
        # Auto-set start time when the rental object is created
        self.__inicio = time.time()
        self.__nickname = nickname
        self.__nome = nome
        self.__preco_base = preco_base
        # Add tracking for rental status and calculated values
        self.__active = True
        self.__elapsed_seconds = 0
        self.__total_price = 0

    @property
    def inicio(self):
        # Only return the stored start time, no modifications
        return self.__inicio

    # Keep your existing read-only properties
    @property
    def nickname(self):
        return self.__nickname
    @property
    def nome(self):
        return self.__nome
    @property
    def preco_base(self):
        return self.__preco_base

2.完善update Method to Track Elapsed Time & Total Price

Your current update calculates values but doesn't store them as instance attributes. Let's fix that, add validation, and mark the rental as inactive once it's returned:

def update(self):
    if not self.__active:
        # Prevent updating already ended rentals
        return
    tempo_fim = time.time()
    self.__elapsed_seconds = tempo_fim - self.__inicio
    # Calculate total price (convert seconds to hours first)
    hours_rented = self.__elapsed_seconds / 3600
    self.__total_price = hours_rented * self.__preco_base
    # Mark rental as inactive after final calculation
    self.__active = False

Add properties to access the calculated values:

@property
def elapsed_hours(self):
    return round(self.__elapsed_seconds / 3600, 2)

@property
def total_price(self):
    return round(self.__total_price, 2)

@property
def is_active(self):
    return self.__active

3. Handle Vehicle Return: Write to CSV & Clean Up Object

To write rental details to a CSV when the vehicle is returned, use Python's built-in csv module. We'll also handle cleaning up the object from active tracking lists.

Example Return Implementation:

import csv

def return_vehicle(aluguer, csv_filename="rentals.csv"):
    aluguer.update()
    if not aluguer.is_active:
        # Prepare human-readable data for CSV
        rental_data = [
            time.ctime(aluguer.inicio),  # Formatted start time
            aluguer.nickname,
            aluguer.nome,
            aluguer.preco_base,
            aluguer.elapsed_hours,
            aluguer.total_price,
            time.ctime()  # Formatted return time
        ]
        # Append to CSV (create file + header if it doesn't exist)
        with open(csv_filename, mode='a', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            # Write header only if file is empty
            file.seek(0, 2)
            if file.tell() == 0:
                writer.writerow(["Start Time", "User Nickname", "Vehicle Name", "Hourly Rate", "Hours Rented", "Total Price", "Return Time"])
            writer.writerow(rental_data)
        print(f"Rental for {aluguer.nome} returned successfully. Details saved to {csv_filename}")
    else:
        print("Failed to return vehicle: rental could not be finalized.")

Cleaning Up the Object:

In Python, objects are automatically deleted by the garbage collector when no references point to them. If you're managing active rentals in a list, remove the object from the list after return:

# Example: Managing active rentals
active_rentals = []
new_rental = Aluguer("john_doe", "Toyota Corolla", 15.0)
active_rentals.append(new_rental)

# When returning the vehicle
return_vehicle(new_rental)
active_rentals.remove(new_rental)
# Now, if no other variables reference new_rental, it will be cleaned up automatically

4. Check if a Rental is Active

Use the is_active property we added to quickly check rental status:

if rental.is_active:
    print(f"Rental for {rental.nome} is still in progress.")
else:
    print(f"Rental for {rental.nome} has been returned.")

This explicit status flag is more reliable than inferring status from elapsed time (it leaves room for future edge cases like pausing rentals).


内容的提问来源于stack exchange,提问作者Sandra Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:26:29