如何在不同类中使用变量?跨文件类字段累加需求实现
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.
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 upself.resultwhen the class is instantiated - Changed the local
result = a+btoself.result = a+bso the value persists on the instance
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
Calculatorclass from its file - Changed
'result'tocalculator_instance.resultto reference the actual field - Added a parameter to accept the
Calculatorinstance (this is the cleanest way to share data between classes)
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)
- Forgetting
self.: If you don't useself.resultin 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 withinstance.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

