0

Can I just call the get_random_items() function directly on the random_items attribute or is this considered bad practice in Python?

class Items(object):

    def __init__(self, tools, toys, food):
        self.tools = tools
        self.toys = toys
        self.yellow = food
        self.random_items = self.get_random_items([self.tools, self.toys, self.food])

    def get_random_items(self, item_list)
        # do stuff to get random items..
        return random_items

If this is bad practice, what would be a better way to provide the random_items?

Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
Rotareti
  • 49,483
  • 23
  • 112
  • 108
  • Explain what you're trying to do. – Karoly Horvath May 19 '16 at 14:13
  • I thought `self.random_items` is a property? If not I should refactor the question. – Rotareti May 19 '16 at 14:13
  • I think maybe OP means if `self.random_items` (which is just the return value of the function) should just be replaced with the function. @le0m is that what you mean? – Arc676 May 19 '16 at 14:14
  • Note that a [`property`](https://docs.python.org/2/library/functions.html#property) is something very specific in Python. Since you meant to use the term "attribute", I have edited your title. – Vincent Savard May 19 '16 at 14:18
  • In short: there's nothing wrong with calling a method to set an attribute. We have not enough context about what you are actually trying to do, so it is hard to tell if this particular example is good design. – timgeb May 19 '16 at 14:19
  • I just wonder if it is ok to generate the values of attributes from within the `__init__` function or if it be better to generate the values externally and add them to the instances. Sorry I find it hard to expaint. – Rotareti May 19 '16 at 14:31

1 Answers1

1

It works. But if you do that, the value of random_items will be calculated only one time during __init__. You will always get the old value, although the values of tools, toys or food are currently changed.

You should use here property

class Items(object):

    def __init__(self, tools, toys, food):
        self.tools = tools
        self.toys = toys
        self.yellow = food

    @property
    def random_items(self):
        return self.get_random_items([self.tools, self.toys, self.food])

    def get_random_items(item_list)
        # do stuff to get random items..
        return some_random_items

And you can use random_items like attribute in other functions.

qvpham
  • 1,896
  • 9
  • 17