Python导入的代码需要很长时间才能运行…为什么?

2024-04-26 00:38:28 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是从一个python文件导入到另一个文件的代码。。。你知道吗

class Crop():
    def water(self):
        print('not')

    def harvest(self):
        print('not')

    def __init__(self):
        self.height = 0
class Corn(Crop):
    def water(self):
        self.height = self.height + 2

    def harvest(self):
        if self.height >= 9:
            return 1
        else:
            return 0
class Wheat(Crop):
    def water(self):
        self.height = self.height + 1

    def harvest(self):
        if self.height >= 5:
            return 1
        else:
            return 0
class Irrigator():
    def __init__(self, load):
        self.load = load

    def irrigate(self, field):
        while self.load > 0:
            self.load = self.load - 1
            field.rain()

我把上面的代码导入另一个python文件。。。你知道吗

from farmhelper import *
from random import *

# Field for holding the crops.
class Field():
    def rain(self):
        for i in range(len(self.plants)):
            self.plants[i].water()

    def __init__(self, size, crop):
        self.plants = [0] * size
        for i in range(size):
            self.plants[i] = crop()

class Combine():
    def harvest(self, field):
        quantity = 0
        for i in range(len(field.plants)):
            quantity += field.plants[i].harvest()
        return quantity

# Create fields with 10,000 of each crop

cornField = Field(10000, Corn)
wheatField = Field(10000, Wheat)

# Create irrigators for each field

cornIrrigator = Irrigator(20000)
wheatIrrigator = Irrigator(500)

# Create a combine for harvesting
combine = Combine()


# 90 days ~3 months of growth
for i in range(90):
    # Low chance of rain
    if randint(0, 100) > 95:
        print("It rained")
        cornField.rain()
        wheatField.rain()
    # Always run the irrigators. Since they are never
    # refilled they will quickly run out
    cornIrrigator.irrigate(cornField)
    wheatIrrigator.irrigate(wheatField)

# Gather the crops - DONE
earsOfCorn = combine.harvest(cornField)
headsOfWheat = combine.harvest(wheatField)

# Print the result - DONE
print("Grew", earsOfCorn, "ears of corn")
print("and", headsOfWheat, "heads of wheat")

但由于某些原因,代码运行大约需要2到3分钟。我认为后一个代码有问题。如果有人有办法,让我知道!你知道吗


Tags: ofselffieldforreturndefloadclass
1条回答
网友
1楼 · 发布于 2024-04-26 00:38:28

一个更有效的设计是不要把每一个工厂都作为一个单独的实例来建模。从目前的情况来看,你对一块地的每一个植物都执行完全相同的操作。只需给田地一个大小属性和一个作物属性,这样就可以为每个田地一株植物建模,并将任何与大小相关的输出乘以大小。你知道吗

大致是这样的:

class Field():
    def rain(self):
        self.crop.water()

    def __init__(self, size, crop):
        self.size = size
        self.crop = crop()

class Combine():
    def harvest(self, field):
        quantity = field.crop.harvest() * field.size
        return quantity

相关问题 更多 >