繁体   English   中英

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

[英]Python imported code taking long to run…why?

这是我从一个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分钟。 我认为后面的代码发布有问题。 如果有人有解决方案,我知道!

一种更有效的设计是不将每个工厂建模为单独的实例。 就目前而言,您可以对一个字段的每个植物执行完全相同的操作。 只需为Field赋予大小属性和作物属性,从而为每个田地仅建模一种植物,然后将与大小相关的输出乘以大小即可。

与此类似:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM