Python's Magic Methods in Classes (Quiz)
Become a Member to take the quiz.
Andras on Jan. 10, 2025
In one of the quiz questions I gave this answer:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __getattr__(self, name):
if name == "area":
return self.width * self.height
return super().__getattribute__(name)
which gives correct results for me in Python 3.10.13:
r = Rectangle(4, 5)
print(r.width) # 4
print(r.height) # 5
print(r.area) # 20
print(r.foo) # AttributeError: 'Rectangle' object has no attribute 'foo'
But my answer was rejected saying RecursionError: too much recursion
.
Are you using a different Python version? Or am I missing something else?
Bartosz Zaczyński RP Team on Jan. 13, 2025
@Andras Our quizzes use a Python emulator (Brython 3.9) that runs in your browser on top of JavaScript, so there will occasionally be such discrepancies. You’re not missing anything, and your answer is one hundred percent correct.
Dan Bader RP Team on Jan. 15, 2025
@Andras We’ve just updated the Python execution environment for quizzes and I confirmed that the answer code you posted in your comment now passes successfully. Thanks for the heads up :)
Become a Member to join the conversation.
bhchurch6 on Nov. 6, 2024
I added the methods requested with the following code. As indicated in a previous question, single quotes can be used to deliminate an
'f'
string. The answer provided does not allow again for this option to be used.This code does produce the required result for a
Person('Sonika', 30)
object.