【发布时间】:2023-02-21 14:18:26
【问题描述】:
我正在尝试使用一个类来设置其他类中的变量。我正在使用下面的代码。我期待“是”,因为我在 OtherClass 中调用了方法 check_condition 。我的预期答案是“是”,但得到的是“否”。我不确定缺少什么,希望得到帮助。谢谢
# 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())
我期待输出“是”,但得到“否”
【问题讨论】:
-
y与t.myClass_instance不是同一个对象/实例,请尝试使用t.myClass_instance.do_something() -
我很困惑。我应该在哪里尝试这个?
-
除了实例属性的混淆之外,请注意您在
MyClass.check_condition中有错字——您在本应使用=的地方使用了==。
标签: python python-3.x