3

I am new in Python, and I would like to know: Is possible use one variable in another class?

For example:

class Hello:

    def function_a(self):
        x = 1


class World:

    def function_b(self):
        print(x)


a = Hello()
b = World()
a.function_a()
b.function_b()

How can I share "x" between classes ?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Marty
  • 113
  • 1
  • 4
  • 9

3 Answers3

4

As it is, that can't be done. The simple option is to make x global by adding a global x line to the beginning of each function that uses it.

The best practice would be to avoid globals and pass around objects which hold the shared variables:

class Hello:

    def function_a(self):
        # Stores the x variable in the current instance of Hello
        self.x = 1


class World:

    def function_b(self, a):
        print(a.x)


a = Hello()
b = World()
a.function_a()
b.function_b(a)
Dennis Shtatnov
  • 1,333
  • 11
  • 17
3

Not in that way. Python, like most modern languages, has scopes. You could use globals, but don't get in the habit of that because they are almost always bad practice.

This is the way I would do it.

class Hello:
    def __init__(self, shared):
        self.shared = shared

    def function_a(self):
        self.shared['x'] = 1

class World:
    def __init__(self, shared):
        self.shared = shared

    def function_b(self):
        print(self.shared['x'])

shared = {}
a = Hello(shared)
b = World(shared)
a.function_a()
b.function_b()
Aaron Schif
  • 2,421
  • 3
  • 17
  • 29
  • great example. simple and readable especially with variable choice `shared`. this is not an easy example to search for or find with the complexity of classes. other posts talk about everything except this simple concept – Marc Compere Jun 27 '22 at 01:01
  • changes to `shared` can be made from `function_a()`, `function_b()`, or in main and are reflected in each of the other contexts – Marc Compere Jun 27 '22 at 01:03
2

If you don't want to pass in the variable, you need to make it global:

class Hello:
    def function_a(self):
        global x
        x = 1


class World:
    def function_b(self):
        global x
        print(x)


a = Hello()
b = World()

>>> x = 20
>>> b.function_b()
20
>>> a.function_a()
>>> b.function_b()
1
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76