开发者

Importing values in Python

I have a little module that creates a window (program1). I've imported this into another python program of mine (program2).

How do I make program 2 get self.x and x that's in program1?

This is program1.

import Tkinter

class Class(Tkinter.Tk):

    def __init__(self, parent):

        Tkinter.Tk.__init__(self, parent)
        self.parent = parent

        self.Main()

    def Main(self):
        self.button= Tkinter.Button(self,text='hello')
       开发者_StackOverflow社区 self.button.pack()

        self.x = 34
        x = 62





def run():
    app = Class(None)
    app.mainloop()

if __name__ == "__main__":
    run()


You can access the variable self.x as a member of an instance of Class:

c = Class(parent)
print(c.x)

You cannot access the local variable - it goes out of scope when the method call ends.


I'm not sure exactly what the purpose of 'self.x' and 'x' are but one thing to note in the 'Main' method of class Class

def Main(self):
        self.button= Tkinter.Button(self,text='hello')
        self.button.pack()

        self.x = 34
        x = 62

is that 'x' and 'self.x' are two different variables. The variable 'x' is a local variable for the method 'Main' and 'self.x' is an instance variable. Like Mark says you can access the instance variable 'self.x' as an attribute of an instance of Class, but the method variable 'x' is only accessible from within the 'Main' method. If you would like to have the ability to access the method variable 'x' then you could change the signature of the 'Main' method as follows.

def Main(self,x=62):
    self.button= Tkinter.Button(self,text='hello')
    self.button.pack()

    self.x = 34
    return x

This way you can set the value of the method variable 'x' when you call the 'Main' method from an instance of Class

>> c = Class()
>> c.Main(4)
4

or just keep the default

>> c.Main()
62

and as before like Mark said you will have access to the instance variable 'self.x'

>> c.x
34
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜