0

I want to create a function within a class that can access two different members with the same function. For example in the code below, I want both of the lines below to use the 'apply' function on different variables in the class

print(state.apply(rate))
print(state.apply(wage))

I had thought if I put in a dummy variable in the function definition (called exposure), it would replace it with the variables passed to the function (rate and wage in the example below). What is the correct way of doing this in python 3?

class State():

def __init__(self):
    self.rate = 0
    self.wage = 0

def apply(self, exposure):
    self.exposure = self.exposure - 1
    return self.exposure


state = State()
rate = State.rate
wage = State.wage
print(state.apply(rate))
print(state.apply(wage))

EDIT: I had made a typo where I had State instead of state in each print statement. I have now corrected this

3
  • Your approach makes no sense. Please see e.g. nedbatchelder.com/text/names.html Commented Dec 29, 2014 at 14:59
  • You appear to be confusing to some extent the class, which is named State, and its instances, of which you can make as many as you wish but in the above example make only one, named state. The State class has no rate nor wage (instances have those attributes because their __init__ sets them) and apply can be called on an instance, not on the whole class (and requires the exposure attribute to be there in advance). So, your Q needs much more clarity. Commented Dec 29, 2014 at 15:04
  • Sorry that is a typo which I need to edit. It should be lower case s in each of the print statements Commented Dec 29, 2014 at 15:08

1 Answer 1

4

This would be the only way:

class State:
    def __init__ (self):
        self.rate = 0
        self.wage = 0

    def apply (self, exposure):
        setattr(self, exposure, getattr(self, exposure) - 1)
        return getattr(self, exposure)
>>> state = State()
>>> print(state.apply('rate'))
-1
>>> print(state.apply('wage'))
-1
>>> print(state.apply('wage'))
-2

Note that those are instance variables, so you cannot access them using the type, State, but only using the object, state.

However, I would say, that whatever you are trying, you’re doing it wrong. If you describe your actual problem, we may be able to suggest a way better solution for it instead.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.