Python Processing中如何从主文件向其他类导入变量?
Great question! In Python Processing, unlike Java Processing where main tab variables are automatically accessible globally, you’ll need to use explicit approaches to share variables between the main tab and separate class files. Let’s break down the solutions to your two related questions:
Method 1: Pass Variables as Arguments (Most Recommended)
The cleanest way is to pass the variables directly to your class instance or method when you initialize/call it. This keeps your code decoupled and easy to maintain.
Example: Pass variables to the class constructor
# Main tab x = 10 y = 20 ball = None def setup(): size(400, 400) global ball # Pass x and y when creating the Ball instance ball = Ball(x, y) def draw(): background(0) ball.myMethod()
# Ball.py class Ball: def __init__(self, x_val, y_val): # Store the passed values as instance attributes self.x = x_val self.y = y_val def myMethod(self): # Access the values via self ellipse(self.x, self.y, 20, 20) print(f"Ball position: {self.x}, {self.y}")
Example: Pass variables directly to the method
If you only need the variables for a specific method call instead of the entire instance lifecycle:
# Main tab (inside draw()) ball.myMethod(x, y)
# Ball.py class Ball: def myMethod(self, x_val, y_val): ellipse(x_val, y_val, 20, 20)
Method 2: Use a Shared Global Module
You can create a separate module to hold shared variables, then import that module in both the main tab and your class file.
Example:
# globals.py (create this new tab/file) x = 10 y = 20
# Main tab import globals def setup(): size(400, 400) # You can modify these values later if needed globals.x = 15 def draw(): background(0)
# Ball.py import globals class Ball: def myMethod(self): ellipse(globals.x, globals.y, 20, 20)
Method 3: Import the __main__ Module (Less Recommended)
Python Processing runs the main tab as the __main__ module, so you can import it directly in your class file. This works but creates tight coupling between your class and the main tab, which can make maintenance harder.
Example:
# Ball.py import __main__ class Ball: def myMethod(self): # Access variables directly from __main__ ellipse(__main__.x, __main__.y, 20, 20)
Key Difference from Java Processing
In Java Processing, the main tab is compiled into a class where variables are class-level members, hence globally accessible. Python Processing treats each tab as a separate module, so variables in the main tab (__main__) aren’t automatically available to other modules unless you explicitly share them using the methods above.
内容的提问来源于stack exchange,提问作者Hashmat

