1

Here's an example for explaining my question a little better,

class T:
    def fn(self):
        rest = 'test'
        return rest
    def fn1(self):
        print(rest)

I want to know, if there's any way that I can access the variable defined in functionfn in function fn1.

I looked around and I found that we could make variable global by passing global rest in function fnlike below,In this way I was able to access rest variable in function fn1

def fn(self):
    global rest
    rest = 'test'
    return rest

I want to know if there are any other way that I can access variables across multiple functions all belonging to same class.

Any help is really appreciated, Thanks.

user_12
  • 1,778
  • 7
  • 31
  • 72
  • Take the tour [Python - Object Oriented](https://www.tutorialspoint.com/python/python_classes_objects.htm) – stovfl Jan 13 '20 at 19:23

1 Answers1

4

Use attributes:

class TheClass:
    def __init__(self):
        self.rest = None

    def set_rest(self):
        self.rest = "test"

    def print_rest(self):
        print(rest)

instance = TheClass()
instance.set_rest()
instance.print_rest()
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • thank you, are those the only ways to do it (i.e using global and using attributes)? – user_12 Jan 13 '20 at 19:21
  • @user_12 yes, these are the obvious ways. The whole *point* of local variables is that they are inaccesible outside the function. If you want to share state between functions in your class, then the *obvious* way is to use attributes, don't use globals. – juanpa.arrivillaga Jan 13 '20 at 19:29
  • @juanpa.arrivillaga thanks, also if possible can you tell me why we shouldn't use globals? – user_12 Jan 13 '20 at 19:31
  • 1
    @user_12 long story short: because global mutable state leads to poorly organized code and hard to track down bugs, especially as your code grows and needs to be maintained by more than one person. Heed the wisdom of those that came before you. – juanpa.arrivillaga Jan 13 '20 at 19:32
  • I just tried this and im getting a name error saying 'rest' is not defined – aero8991 Nov 25 '21 at 00:14