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

如何在不同类中使用变量?跨文件类字段累加需求实现

Alright, let's work through this step by step to get your code working as intended. You've got a couple of critical issues in your current snippets that are preventing the functionality you want—let's fix them one by one.


Step 1: Correct the First Class (with addFunction)

Your original addFunction only creates a local result variable, which won't be stored as a field on the class instance. We need to assign the sum to self.result so other classes can access it later. Also, we should initialize the result field in the class constructor to avoid attribute errors.

Here's the fixed first class (save this as, say, calculator.py):

class Calculator:
    def __init__(self):
        # Initialize the result field to a default value
        self.result = 0

    def addFunction(self, a, b):
        # Store the sum in the instance's result field, not a local variable
        self.result = a + b
        return self.result  # Optional, if you want to return the sum directly

Key fixes here:

  • Added __init__ to set up self.result when the class is instantiated
  • Changed the local result = a+b to self.result = a+b so the value persists on the instance

Step 2: Fix the Second Class (with addGroup)

First, you need to import the first class from its file. Then, your addGroup method needs access to an instance of the first class to read its result field—right now you're trying to add 95 to the string 'result', which will throw a type error.

Save this as, say, score_processor.py:

from calculator import Calculator

class ScoreProcessor:
    def addGroup(self, calculator_instance):
        # Access the result field from the passed Calculator instance
        score = 95 + calculator_instance.result
        return score

Key fixes here:

  • Imported the Calculator class from its file
  • Changed 'result' to calculator_instance.result to reference the actual field
  • Added a parameter to accept the Calculator instance (this is the cleanest way to share data between classes)

Step 3: Putting It All Together

To use these classes, you'll create instances of each and pass the Calculator instance to the ScoreProcessor method:

from calculator import Calculator
from score_processor import ScoreProcessor

# Create a Calculator instance and run the addition
calc = Calculator()
calc.addFunction(20, 30)  # This sets calc.result to 50

# Create a ScoreProcessor instance and calculate the final score
scorer = ScoreProcessor()
final_score = scorer.addGroup(calc)
print(final_score)  # Output: 145 (95 + 50)

Common Pitfalls to Avoid
  • Forgetting self.: If you don't use self.result in the first class, the value is only stored as a local variable and can't be accessed outside the method.
  • Using string literals instead of attributes: 'result' is just text—you need to reference the instance's attribute with instance.result.
  • Not importing the first class: Make sure the second file can access the first class via an import, and that both files are in the same directory (or properly configured in your Python path).

内容的提问来源于stack exchange,提问作者Mateusz Nerkowski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:03:22