How to Fix Common Python OOP Errors: A Step‑by‑Step Guide
This article walks through a Python object‑oriented programming issue raised by a community member, demonstrates how to correct string‑formatting mistakes, indentation errors, and undefined variable problems, and provides a complete, runnable code example to solidify OOP fundamentals.
1. Introduction
Hello everyone, I am PiPi. A few days ago, a member of the Python Silver Group asked an object‑oriented programming question, as shown in the screenshot below.
The following image shows the runtime error.
2. Implementation Process
Guidance from a contributor suggested that the issue was caused by repeated string formatting using an f prefix; removing the f resolves the first problem.
After fixing that, a new undefined‑variable error appeared due to incorrect indentation. Adjusting the indentation revealed another bug, where class names were missing when invoking methods.
Similar issues appeared in other parts of the code.
A correct implementation was provided as follows:
class Student(object):
# Define a Student class
def __init__(self, name, score):
# Two attributes: name and score
self.name = name
self.score = score
def set_score(self, score):
if int(score) >= 0 and int(score) <= 100:
self.score = score
else:
raise(ValueError("Score must be between 0 and 100"))
# Print each student's name and score
def print_score(self):
print("姓名是{},分数是{}".format(self.name, self.score))
if __name__ == '__main__':
Mable = Student("Mable", 100)
Mable.print_score()
Mable.set_score(90)
Mable.print_score()
Mable.set_score(120)
Mable.print_score()This resolved the user's issues and reinforced the importance of solid OOP fundamentals.
3. Summary
The article presented a Python OOP problem, analyzed the errors, and provided a complete code solution to help readers overcome similar challenges.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
