0

I'm trying to set a variable and be able to change and store that variable using set and gets. The current output is:

0

0

I'm trying to get it to be:

0

2

Can some one help me understand how to change a value and then use it later in python? Kind of like a toggle?

class Spammer: 
    def __init__(self, spam = 0): 
        self._spam = spam 

        # getter method 
    def get_spam(self): 
            return self._spam 

        # setter method 
    def set_spam(self, x): 
     if x == 1:  
         return self._spam+1

     if x== 0:
         return self._spam
 spammer=Spammer()

 print (spammer.get_spam())
 spammer.set_spam(1)
 print(spammer.get_spam())
  • 3
    `set_spam()` returns a value, but it never actually sets the value of self.spam. Is that intentional? – John Gordon Jan 15 '20 at 22:24
  • set the value of `self._spam` in `set_spam`, just like you did in `__init__` – nlloyd Jan 15 '20 at 22:25
  • `set_spam` is a misleading name, and probably doesn't need to return a value. Also, it's unclear why you would want to call `set_spam` with an argument of 0, rather than just not call it in the first place. – chepner Jan 15 '20 at 22:29
  • Using setters and getters is not Pythonic, you can just directly access the attribute like `spammer._spam` and `spammer._spam = 1`. See this thread https://stackoverflow.com/a/36943813/3620725 – pyjamas Jan 15 '20 at 22:40

1 Answers1

0

There is an @property decorator builtin so you could do the following:

class Spammer: 
    def __init__(self, spam = 0): 
        self._spam = spam 

    @property
    def spam(self): 
        return self._spam

    @spam.setter
    def spam(self, new_spam):
        self._spam = new_spam
Bugbeeb
  • 2,021
  • 1
  • 9
  • 26