【问题标题】:Use another class to set variable value of another class使用另一个类设置另一个类的变量值
【发布时间】: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())

我期待输出“是”,但得到“否”

【问题讨论】:

  • yt.myClass_instance 不是同一个对象/实例,请尝试使用 t.myClass_instance.do_something()
  • 我很困惑。我应该在哪里尝试这个?
  • 除了实例属性的混淆之外,请注意您在MyClass.check_condition 中有错字——您在本应使用= 的地方使用了==

标签: python python-3.x


【解决方案1】:

如果您希望MyClass 的每个实例都共享同一个my_variable,您应该将其设为类属性,并将操作它的方法设为类方法:

# 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"

【讨论】:

    【解决方案2】:

    我认为问题是您在 check_condition(self) 中使用 == 而不是 =

    def check_condition(self):
        self.my_variable = True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多