0

Is there any way to import a variable from the main file to another class.

For instance:

# main tab

x = 10
y = 20

def setup():
    size(400,400)

def draw():
    background(0)
# Ball.py 

class Ball:

def myMethod(self):
# here I want to import the 'x or y' variables from the main file.

In Java Processing variables declared in the main tab can be used from everywhere, but when it comes to Python Processing that's not the case.

Hashmat
  • 707
  • 1
  • 8
  • 16

1 Answers1

3

Transferring Data Between Files

You can transfer data between files, if that is what you are trying to do. You would be essentially creating your own modules.

from main import x, y

Something along these lines

Using Data from Outside a Class Inside the Class

I think you are just wanting to use the x and y variables inside of the ball class? To do this you can create an init method where you pass the variable into when you create the ball object.

class Ball:
  """ You can use the x and y variables anywhere in this class"""
  def __init__(self, x, y):
    self._x = x
    self._y = y

  def myMethod(self):
    print(self._x)
    print(self._y)

b1 = Ball(10, 20)
b1.myMethod()

Or You could just pass the variables into the constructor

x = 10
y = 10
b2 = Ball(x, y)