Python:如何在类实例之间传递变量或获取调用方? [英] Python: How do I pass variables between class instances or get the caller?

查看:254
本文介绍了Python:如何在类实例之间传递变量或获取调用方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class foo():
  def __init__(self)
    self.var1 = 1

class bar():
  def __init__(self):
    print "foo var1"

f = foo()
b = bar()

在foo中,我正在执行将"var1"设置为1的操作 在bar中,我想访问var1的内容

In foo, I am doing something that produces "var1" being set to 1 In bar, I would like to access the contents of var1

如何从bar的实例b中访问foo的类实例f中的var1

How can I access var1 in the class instance f of foo from within the instance b of bar

基本上,这些类是不同的wxframe.因此,例如,在一个窗口中,用户可能正在输入输入数据,在第二个窗口中,用户使用该输入数据来生成输出.在C ++中,我将有一个指向调用者的指针,但我不知道如何在python中访问调用者.

Basically these classes are different wxframes. So for example in one window the user may be putting in input data, in the second window, it uses that input data to produce an output. In C++, I would have a pointer to the caller but I dont know how to access the caller in python.

推荐答案

作为wxPython中不同页面访问和编辑相同信息的一般方法,请考虑在MainFrame(或您调用的任何东西)中创建info类的实例.它)类,然后将该实例传递到它创建的任何其他页面上.例如:

As a general way for different pages in wxPython to access and edit the same information consider creating an instance of info class in your MainFrame (or whatever you've called it) class and then passing that instance onto any other pages it creates. For example:

class info():
    def __init__(self):
        self.info1 = 1
        self.info2 = 'time'
        print 'initialised'

class MainFrame():
    def __init__(self):
        a=info()
        print a.info1
        b=page1(a)
        c=page2(a)
        print a.info1

class page1():
    def __init__(self, information):
        self.info=information
        self.info.info1=3

class page2():
    def __init__(self, information):
        self.info=information
        print self.info.info1

t=MainFrame()

输出为:

initialised
1
3
3

信息只有在证明只有一个实例但页面1已将info1变量更改为3且页面2已注册该更改后才被初始化.

info is only initialised once proving there is only one instance but page1 has changed the info1 varible to 3 and page2 has registered that change.

这篇关于Python:如何在类实例之间传递变量或获取调用方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆