0

我有一个具有三个具有不同属性的函数的类:

 class Weather:
        def __init__(year,month,day):
            #do something with year, month and day
        def crops(beans,wheat):
            #do something with beans and wheat
        def vegetables(tomato,garlic)
            #do something with tomato, garlic and beans

我需要beans在两者中使用cropsvegatables但 bean 是crops. 这是可能的还是我需要包含beans在内__init__才能在多个功能中使用它?

4

2 回答 2

2

是的,__init__你会做类似的事情

self.beans = beans

这意味着 bean 成为一个类变量并且在所有类方法中都可用。

这是有关python中的类的一些文档

于 2013-09-12T08:43:28.497 回答
1

beans不是函数“属性” crops()。它是该函数的参数。您可以通过执行以下操作使其成为Weather 对象的属性:

def crops(self, beans):
    self.beans = beans

你可以用任何方法做到这一点,而不仅仅是__init__()

这将在内部访问vegetables()

def vegetables(self, tomatoes):
    print self.beans

只要你crops()之前至少打过一次电话vegetables()

您是否应该在这些方法中执行此操作,而不是在其中初始化共享数据,__init__()这是一个设计问题,对于一个人为的示例来说是不可能回答的。

此外,您拥有的所有方法可能都应该self作为第一个参数。(请参阅每个 Python 教程。)除非您打算将它们称为Weather.crops(...),即仅将类用作命名空间,但这会令人困惑。最好将它们作为模块级函数或用于@staticmethod明确您的意图。

于 2013-09-12T09:10:04.827 回答