python船只系统

以下是一个简单的python船只系统的代码:

class Ship:
    def __init__(self, name, capacity):
        self.name = name
        self.capacity = capacity
        self.cargo = []
    
    def add_cargo(self, item):
        if len(self.cargo) < self.capacity:
            self.cargo.append(item)
            print(f"{item} added to {self.name}")
        else:
            print(f"{self.name} is full and cannot add {item}")
    
    def remove_cargo(self, item):
        if item in self.cargo:
            self.cargo.remove(item)
            print(f"{item} removed from {self.name}")
        else:
            print(f"{item} is not found in {self.name}")
    
    def display_cargo(self):
        print(f"{self.name} cargo: {', '.join(self.cargo)}")


ship1 = Ship("Ship 1", 3)
ship1.add_cargo("Item 1")
ship1.add_cargo("Item 2")
ship1.add_cargo("Item 3")
ship1.display_cargo()
ship1.add_cargo("Item 4")
ship1.remove_cargo("Item 2")
ship1.display_cargo()

运行上述代码将输出以下结果:

Item 1 added to Ship 1
Item 2 added to Ship 1
Item 3 added to Ship 1
Ship 1 cargo: Item 1, Item 2, Item 3
Ship 1 is full and cannot add Item 4
Item 2 removed from Ship 1
Ship 1 cargo: Item 1, Item 3

这段代码创建了一个名为Ship的船只类,每艘船都有一个名称和一个容量限制。船只可以添加、移除和显示货物。在示例中,我们创建了一个船只实例ship1,并对其进行了一系列操作。

你可能感兴趣的:(python,开发语言)