简体   繁体   中英

Python - accessing variable from function in class

I have a class as given below and I want to access some of variables located inside function of that class. The structure is as below:

class access_all_elements:

   def RefSelect_load_file(): 

       reffname = askopenfilename(filetypes=(("XML files", "*.xml"),
                                                 ("All files", "*.*") ))
       if reffname: 
          ReferenceXML.insert(END,fileOpen.read())  
          recovering_parser = etree.XMLParser(recover=True)
          AdasReference = etree.parse(reffname, parser=recovering_parser).getroot()
          AdasReferenceString = etree.fromstring(ToStringAdasReference)
          TimeReferenceTest = AdasReferenceString.findall("{http://www.google.com/car}bmw")
      return TimeReferenceTest

  def CopySelect_load_file(): 
    #same code as above, but for loading another file in same GUI

Description of code

1). class access_all_elements: class to access all elements inside

2). def RefSelect_load_file(): function inside class that loads xml file

3). ReferenceXML.insert(END,fileOpen.read()) insert filepath in text box inside gui

4). AdasReference: Parse xml file located in reffname

5). TimeReferenceTest: this extracts all the elements from xml having label car The output of this variable looks like: [<Element {http://www.google.com/car}bmw at 0x279ff08>, <Element {http://www.google.com/car}bmw at 0x279ffa8>.....]

5). return TimeReferenceTest I want to return the value of this variable when function is called

What I want:

There is another function outside this class namely callback which uses one of the variable which is located in access_all_elements class and that variable is TimeReferenceTest . I want to access the value of this variable in the below given function. The value is mentioned in 5th point above. The function outside class looks like below:

        def callback():

            toplevel = Tk()
            toplevel.title('Another window')
            RWidth=Root.winfo_screenwidth()
            RHeight=Root.winfo_screenheight()
            toplevel.geometry(("%dx%d")%(RWidth,RHeight))

            for i,j in zip(TimeReferenceTest,TimeCopyTest): #TimeCopyTest is also like TimeReferenceTest defined in above class under CopySelect_load_file() function,but not mentioned here
                    .......

To put it simply, out of entire entity of RefSelect_load_file() function I only want to access the value of variable TimeReferenceTest in line for i,j in zip(TimeReferenceTest,TimeCopyTest) when callback is function is executed

What I tried and What this is all about

First all, I am making a GUI in Tkinter and trying to bind all the code I wrote with that gui. Callback is invoked when someone presses button to compare two xml files.

What I tried so far is the approach of encapsulating both functions into same class as shown above to access its variables. I call the class in following manner:

c = access_all_elements()
c.RefSelect_load_file()

The problem here is I know this function is defined in a way to open file dialogue box, but I want to return value of only TimeReferenceTest when I call it in callback function. So is there any way you can suggest where i can access that variable without executing entire function?

I think you might be looking for something that does not exist. If you want 2 functions to share specific variables you do not have too many options.

As you have already mentioned one option is to put both functions into a class and make the variables you want shared "members":

Class MyFuncs:
    def __init__(self, someVal):
        self.val = someVal
    def foo(self):
        self.val = "FOO"
    def bar(self):
        self.val = self.val + "BAR"

Another option might be to use closures:

def GetFunctions():
    sharedArray = [] # put shared values here
    def foo():
        sharedArray.append("FOO")
    def bar():
        sharedArray.append("BAR")
    def printAll():
        for word in sharedArray:
            print(word)
    return (foo,bar,printAll)

Though I do not really recommend this method.

Of course you could also just pass things into the function as parameters. If the functions aren't logically coupled then this is what you should be doing anyway.

If none of these options suit your fancy then the problem is with your design. Your code should be organized in a way that is intuitive and should make logical sense! If you want this functionality simply for convenience (perhaps you do not want to put too many parameters on your functions) then you probably will not find the answer you are looking for.

Hope this helps! :)

I think you should make the functions part of the instance rather than static class methods. You can then make TimeReferenceTest also an attribute, which you can then access from outside the instance:

class Access_all_elements():
    def __init__(self):
        self.timeReferenceTest = None
        self.timeCopyTest = None

    def refSelect_load_file(self):
        ...
        self.timeReferenceTest = adasReferenceString.findall(...)
        ...
...
c = Access_all_elements()

# get value as return value from function
trt = c.RefSelect_load_file()
print("  TimeReferenceTest = %s" % trt)
...
# use the value in callback
def callback():
    ...
    for i,j in zip(c.timeReferenceTest,c.timeCopyTest): ...

This assumes c is global, though it would be better if you passed it in.

(Note: Your naming scheme seems backwards which makes your code hard to grasp. PEP8 suggests that classes should begin with an uppercase, and functions and attributes should begin with lowercase. I tried to adopt that in my answer to make the code easier to understand for most python programmers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM