【问题标题】:Python: From outside Class access to variable in method other than __self__(init)Python:从外部类访问__self__(init)以外的方法中的变量
【发布时间】:2013-05-06 09:30:56
【问题描述】:

http://effbot.org/tkinterbook/tkinter-dialog-windows.htm 有一个例子 还有一件事我不明白:

class Dialog(Toplevel):

    ...

        self.result = None

...

class MyDialog(Dialog):

    def apply(self):
        first = int(self.e1.get())
        second = int(self.e2.get())
        self.result = first, second

d = MyDialog(root)
print d.result

他们通过引用d.resultapply 方法中访问self.result

我尝试用我自己的简单示例来重构它:

class Mother(object):
  def __init__(self):
    self.result = None
  def apply(self):
    pass

class Class(Mother):
  def apply(self):
    self.result = "hello"

d = Class()
print d.result

print d.result 的输出是 None 而不是 "hello"

请帮忙。

【问题讨论】:

    标签: python class variables methods


    【解决方案1】:

    您从未调用 d.apply()result 设置为“你好”。

    【讨论】:

    • 更详细地说,所呈现的类层次结构与Toplevel 背后的最大区别在于,很难用心说出Toplevel 做了什么。如果我们可以假设在Toplevel.__init__() 中的某个地方有一个调用self.apply(),我们就发现了区别。
    猜你喜欢
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多