Use another class to set variable value of another class

Question:

I am trying to use one class to set the variable in other class. I am using the code below. I am expecting "Yes" since I have called the method check_condition in OtherClass . My expected answer is "Yes" but am getting "No". I am not sure of what am missing and will appreciate assistance. Thanks


# class meant to set Myclass.my_variable to True or False
class OtherClass(object):
    def __init__(self):
  
        self.bole = 777
        self.myClass_instance = MyClass()

    def some_method(self):
        if type(self.bole) == int:
            self.myClass_instance.check_condition()
 
class MyClass:
    def __init__(self):
        self.my_variable = False
    
    def check_condition(self):
        self.my_variable = True
    
    def do_something(self):
        if self.my_variable:
            return "Yes"
        else:
            return "No"

t = OtherClass()
t.some_method()
y = MyClass()
print(y.do_something())

I am expecting output of "Yes", but am getting "No"

Asked By: research comp5800

||

Answers:

If you want every instance of MyClass to share the same my_variable, you should make it a class attribute, and make the methods that operate on it class methods:

# class meant to set Myclass.my_variable to True or False
class OtherClass(object):
    def __init__(self):
        self.bole = 777

    def some_method(self):
        if type(self.bole) == int:
            MyClass.check_condition()
 
class MyClass:
    my_variable = False
    
    @classmethod
    def check_condition(cls):
        cls.my_variable = True
    
    @classmethod
    def do_something(cls):
        if cls.my_variable:
            return "Yes"
        else:
            return "No"

t = OtherClass()
t.some_method()
y = MyClass()
print(y.do_something())  # prints "Yes"

If you use instance attributes, you need to make sure you’re calling do_something on the same instance that you called check_condition on:

class OtherClass(object):
    def __init__(self):
        self.bole = 777
        self.myClass_instance = MyClass()

    def some_method(self):
        if type(self.bole) == int:
            self.myClass_instance.check_condition()
 
class MyClass:
    def __init__(self):
        self.my_variable = False
    
    def check_condition(self):
        self.my_variable = True
    
    def do_something(self):
        if self.my_variable:
            return "Yes"
        else:
            return "No"

t = OtherClass()
t.some_method()
y = t.myClass_instance
print(y.do_something())  # prints "Yes"

Note that in both cases you need to fix the typo in MyClass.check_condition so that it actually sets my_variable to True.

Answered By: Samwise
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.