python中的类交互

时间:2019-03-07 12:55:13

标签: python python-3.x

我正在编写一个植物育种程序,到目前为止有点粗略,但这是我第一个面向对象的编程...

import requests
import random

class environment:
    def __init__(self, weather = None, temperature = None, soil_type = None):
        self.weather = weather
        self.temperature = temperature
        self.soil_type = soil_type

    def get_weather(self):
        self.zip_code = input("Enter your zip code to get weather info: ")
        self.url = "http://api.openweathermap.org/data/2.5/forecast?appid=a9fed4c32128f18e6142d3bd49fb5f7d&units=metric&zip=" + self.zip_code
        self.response = requests.get(self.url) 
        self.result = self.response.json()
        if self.result["cod"] != "404":
            self.weather = self.result['list'][0]['weather'][0]['description']
            self.temperature = self.result['list'][0]['main']['temp']

            print("Weather: {}".format(self.result['list'][0]['weather'][0]['description']))
            if "rain" in self.weather.lower() and "drizzle" not in self.weather.lower():
                print("You need to think about adjusting watering amount.")
            elif "drizzle" in self.weather.lower():
                print("You need to think about adjusting watering amount, but not much adjustment.")
            elif "clouds" in self.weather.lower():
                print("Moderate sunshine.")
            elif "clear sky" in self.weather.lower():
                print("Sunshine, sunshine, sunshine...")

            print("Temperature: {} °C".format(self.result['list'][0]['main']['temp']))
            if self.temperature >= 35:
                print("Temperature is high.")
            elif 35 > self.temperature >= 10:
                print("Temperature is moderate.")
            elif 10 > self.temperature >= 0:
                print("Temperature is low.")
            else:
                print("Too low for the plant to survive.")

        else:
            print("Zip code not found.")

    def choose_soil_type(self):
        self.soil_type = input("Please choose soil type among these - alkaline, neutral, acidic: ")

class plants:
    def __init__(self, preferred_sunshine = None, preferred_water = None, preferred_fertilizer = None, preferred_temp = None, preferred_soil = None):
        self.preferred_sunshine = preferred_sunshine
        self.preferred_water = preferred_water
        self.preferred_fertilizer = preferred_fertilizer
        self.preferred_temp = preferred_temp
        self.preferred_soil = preferred_soil

    def choose_plant(self):
        self.choose = input("Please choose your plant to breed: ")
        if self.choose == "lemon":
            self.preferred_sunshine = 9
            self.preferred_water = 5
            self.preferred_fertilizer = 3
            self.preferred_temp = "high"
            self.preferred_soil = "neutral"
        elif self.choose == "blueberry":
            self.preferred_sunshine = 6
            self.preferred_water = 8
            self.preferred_fertilizer = 5
            self.preferred_temp = "moderate"
            self.preferred_soil = "acidic"
        elif self.choose == "pear":
            self.preferred_sunshine = 3
            self.preferred_water = 3
            self.preferred_fertilizer = 7
            self.preferred_temp = "low"
            self.preferred_soil = "alkaline"
        else:
            print("not a valid plant")

class treatment:
    def __init__(self, water = 0, fertilizer = 0, weed = True):
        self.water = water
        self.fertilizer = fertilizer
        self.weed = weed

    def provide_water(self):
        self.water = input("Please enter the amount of water: ")
        if self.water == self.preferred_water:
            self.water_score = 10
        elif preferred_water - 2 <= self.water <= self.preferred_water + 2:
            self.water_score = 7
        else:
            self.water_score = 4        
        return self.water_score

    def provide_fertilizer(self):
        self.fertilizer = input("Please enter the amount of fertilizer: ")
        if self.fertilizer == self.preferred_fertilizer:
            self.fertilizer_score = 10
        elif preferred_fertilizer - 2 <= self.water <= self.preferred_fertilizer + 2:
            self.fertilizer_score = 7
        else:
            self.fertilizer_score = 4  

    def remove_weed(self):
        count = 0
        while self.weed == True:
            x = 1* random.random()
            count += 1
            if x < 0.3:
                self.weed == False
                print("You have removed the weeds", count, "times to help the plant grow. Good job!")
                break
        if count <= 3:
            self.weed_score = 10
        else:
            self.weed_score = 5





a = environment()
a.get_weather()
a.choose_soil_type()
b = plants()
b.choose_plant()
c = treatment()
c.provide_water()

我想知道如何在类之间进行交互...

Enter your zip code to get weather info: 94560
Weather: light rain
You need to think about adjusting watering amount.
Temperature: 8.05 °C
Temperature is low.
Please choose soil type among these - alkaline, neutral, acidic: acidic
Please choose your plant to breed: lemon
Please enter the amount of water: 5
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-88-50fbdf0f3aa5> in <module>
    123 b.choose_plant()
    124 c = treatment()
--> 125 c.provide_water()

<ipython-input-88-50fbdf0f3aa5> in provide_water(self)
     82     def provide_water(self):
     83         self.water = input("Please enter the amount of water: ")
---> 84         if self.water == self.preferred_water:
     85             self.water_score = 10
     86         elif preferred_water - 2 <= self.water <= self.preferred_water + 2:

AttributeError: 'treatment' object has no attribute 'preferred_water'

该程序会产生如上所述的错误...我知道preferred_water不在处理对象中,但是我想根据我在“ choose_plant”函数中的选择,从“ plants”类中获取信息。 / p>

我也想根据天气情况调整治疗量。但是现在我的课是独立进行的,哈哈...我应该如何开始? :)任何评论都会有所帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

在这一点上,treatmentplant实例彼此独立。在plant实例内部无法访问treatment数据。您想要的是相关的处理方式,以便treatment实例可以查看和使用plant实例。

因此,在您的treatment中,您想添加以下内容:

class treatment:
    def __init__(self, plant, water = 0, fertilizer = 0, weed = True):
        self.water = water
        self.fertilizer = fertilizer
        self.weed = weed
        self.plant = plant

这意味着,在创建treatment对象时,它需要一个plant与之相关的treatment对象。

然后您将要创建一个这样的治疗实例:

b = plants()
c = treatment(b) # create treatment, while passing along the plant instance. 

然后在provide_water函数中,您可以访问plant实例。

def provide_water(self):
        self.water = input("Please enter the amount of water: ")
        if self.water == self.plant.preferred_water:
            self.water_score = 10