-1

Given the class:

class MyClass:
    def __init__(self):
        self.log = []
        return

    def fitness(self, x):
        return x*x

I want to be able to store into the log attribute, the output to each call of the fitness method. In order to have the following:

my_obj = MyClass()

my_obj.fitness(3)
# Expected output 9
my_obj.fitness(6)
# Expected output 36

my_obj.log 
# Expected output [9, 36]

I was thinking about a method decorator, but I don't know how to pass the attribute as argument. I need the log attribute to be embedded in the class and not an external variable. I am using python 3.

Jason Hu
  • 6,239
  • 1
  • 20
  • 41
Simone
  • 17
  • 2
  • there is no rule says decorator must refer to an external variable. this must be a duplicated question. – Jason Hu Nov 20 '17 at 21:13
  • 4
    Just add `self.log.append(x*x)` in the fitness method before you return? – bphi Nov 20 '17 at 21:14
  • In `fitness`, store the result of `x * x` in a variable, add that result to the log and then return it. –  Nov 20 '17 at 21:14
  • Is it acceptable to modify `MyClass.fitness`? – wim Nov 20 '17 at 21:14
  • 1
    Possible duplicate of [Python class method decorator w/ self arguments?](https://stackoverflow.com/questions/11731136/python-class-method-decorator-w-self-arguments) –  Nov 20 '17 at 21:19
  • A decorator would really make sense here only if you wanted to modify the behavior of several methods -- but in that case how would you tell is a given output comes from `fitness` or some other method? If you do want to log multiple methods, a log which is a dictionary keyed by the method names would make more sense. – John Coleman Nov 20 '17 at 21:20

2 Answers2

1

You don't need a decorator, just edit the fitness method to modify the object log variable:

class MyClass:
    def __init__(self):
        self.log = []
        return

    def fitness(self, x):
        self.log.append(x*x)
        return x*x
Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38
0

What you need to do is have the fitness method modify the log attribute directly:

def fitness(self, x):
    self.log.append(x*x)