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

如何从类中获取实例变量用于带输入的if语句?代码问题咨询

How to Access Instance Variables for Conditional Checks with User Input

Hey there! Let's tackle your questions—first fixing the code you wrote, then walking through the general approach for using instance variables with input-driven conditionals.

Fixing Your Code Issues

Let's start with the code you shared, since it has a few clear syntax and logic problems:

class test: 
    def __init__(self, maths, english): 
        self.maths = maths 
        self.english = english 
exam = test(maths, english) 
testchecker = input("which test") 
if testchecker == self.english == true: 
    print("you have passed the test")

Here's what's going wrong, and how to fix each issue:

  • self can't be used outside class methods: self is only valid inside the class's functions (like __init__). To access the instance variables, you need to use your instance name exam instead—so exam.english instead of self.english.
  • Python boolean values are capitalized: true is not a valid keyword; you need to use True (with a capital T). That said, your conditional logic here doesn't make much sense as written—you probably want to check if the input matches a subject, then verify if that subject's score is passing.
  • Undefined variables when creating the instance: maths and english aren't assigned any values before you pass them to test(). You need to define these first (e.g., set them to scores like 75 or 50).
  • Conditional structure is off: Your if testchecker == self.english == true line mixes comparing the input subject name with the score value, which won't work. You need to first check which subject the user is asking about, then check if that subject's score meets your passing criteria.

Here's a revised version of your code that works (assuming a passing score is 60 or higher):

# Follow PEP8: Class names should use PascalCase
class Test:
    def __init__(self, maths, english):
        self.maths = maths
        self.english = english

# First define your scores
maths_score = 82
english_score = 65
# Create an instance of the Test class
exam = Test(maths_score, english_score)

# Get and clean up user input
testchecker = input("Which test would you like to check? (maths/english): ").strip().lower()

# Check the input and verify the score
if testchecker == "english":
    if exam.english >= 60:
        print("You have passed the English test!")
    else:
        print("You didn't pass the English test.")
elif testchecker == "maths":
    if exam.maths >= 60:
        print("You have passed the Maths test!")
    else:
        print("You didn't pass the Maths test.")
else:
    print("Oops, please enter either 'maths' or 'english'.")

General Approach for Using Instance Variables with Input-Driven Conditionals

If you want to generalize this pattern, here's the step-by-step process:

  1. Create your class and instance: Define your class with an __init__ method to set up instance variables, then create an instance of the class with actual values.
    class StudentExam:
        def __init__(self, science, history):
            self.science = science
            self.history = history
    
    student = StudentExam(science=70, history=55)
    
  2. Get and process user input: Use input() to get the user's choice, and clean it up (e.g., strip() to remove extra spaces, lower() to make it case-insensitive).
  3. Access instance variables via the instance: Use the instance name (like student) followed by a dot and the variable name (like student.science) to access the value.
  4. Build your conditional logic: Match the user's input to the relevant instance variable, then check if that variable meets your desired condition (e.g., score >= 60, boolean value is True, etc.).

内容的提问来源于stack exchange,提问作者Zuaibh Malik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:14:43