Python changing class variables

49,992

Solution 1

I'm not sure what possible use you have for this, but...

You want to manipulate a class variable, but you keep addressing instance variables. If you want a class variable, use a class variable!

class Yes:
    a = 1 # initialize class var.
    def __init__(self):
        self.a = 1 # point of this is what?

    def yes(self):
        if Yes.a==1: # check class var
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if Yes.a==1: # check class var
            print "No"
        else:
            print "Yes, but no"
        Yes.a-=1 # alter class var

Solution 2

It appears what you want to use is a static variable rather than an instance variable. A static variable is shared between all the instances of the class.

class Yes:
    a = 1
    def __init__(self):
        pass

    def yes(self):
        if Yes.a==1:
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if Yes.a==1:
            print "No"
        else:
            print "Yes, but no"
        Yes.a-=1 #Note this line

Yes().yes()
No().no()
Yes().yes()
No().no()

Will output:

Yes
No
No, but yes
Yes, but no
Share:
49,992
user2154113
Author by

user2154113

Updated on March 21, 2020

Comments

  • user2154113
    user2154113 about 4 years

    Okay, I'll try and be extremely clear this time.

    class Yes:
    
        def __init__(self):
            self.a=1
    
        def yes(self):
            if self.a==1:
                print "Yes"
            else:
                print "No, but yes"
    
    class No(Yes):
    
        def no(self):
            if self.a==1:
                print "No"
            else:
                print "Yes, but no"
            self.a-=1 #Note this line
    

    Now, while running:

    Yes().yes()
    No().no()
    Yes().yes()
    No().no()
    

    I want it to print out:

    Yes
    No
    No, but yes
    Yes, but no
    

    It gives me:

    Yes
    No
    Yes
    No
    

    Now, I know the reason why is because I'm only changing the value of Self.a in the No class(Remember that line?). I want to know if there is anyway to change it in the Yes class while still in the No class (like if there was something that I could plug in in place of the self.a-=1 that would work).