Comparing equality of classes with a variable number of attributes #321
edoardob90
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
In the Intro Tutorial's notebook on Object-oriented, we explored Python's special methods, like
__eq__
to define the behavior or the equality operator with custom classes. ExampleBut what if I have a class with a variable number of attributes? How can I write a
__eq__
method? The key is thevars()
built-in function, which for an object tries to call the method__dict__
. From the docs: "A dictionary or other mapping object used to store an object’s (writable) attributes." Based on that, here's an example class where we can usevars()
and__dict__
to define__eq__
even if we don't know how many attributes we have:Beta Was this translation helpful? Give feedback.
All reactions