You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Processing中如何从主文件向其他类导入变量?

How to Import Variables from the Main File in 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:

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)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:12:43