multigoodverse
multigoodverse

Reputation: 8072

Using attributes among methods within a class

I have a class with three functions with different attributes:

 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

I need to use beans inside both crops and vegatables but beans is an attribute of crops. Is this possible or I need to include beans inside __init__ to be able to use it in more than one function?

Upvotes: 0

Views: 68

Answers (2)

millimoose
millimoose

Reputation: 39950

beans is not an "attribute" of the crops() function. It's a parameter to that function. You can make it an attribute of the Weather object by doing:

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

You can do this in any method, not just __init__()

This will be accessible inside vegetables() with:

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

as long as you call crops() at least once before vegetables().

Whether you should do this in these methods, as opposed to initialising shared data in __init__() is a design issue that's impossible to answer for a contrived example.

Also, all the methods you have should probably have self as the first parameter. (See every Python tutorial ever.) Unless you aim to call them as Weather.crops(...), i.e. using the class as just a namespace, but that is confusing. Better have them as module-level functions or use @staticmethod to make your intent clear.

Upvotes: 1

Simon
Simon

Reputation: 6363

Yes, in __init__ you would do somthing like

self.beans = beans

That means that beans becomes a class variable and is available in all class methods.

Here's some documentation on classes in python

Upvotes: 2

Related Questions