Created
September 22, 2011 14:03
-
-
Save pasberth/1234844 to your computer and use it in GitHub Desktop.
Python版の iffattrs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def iffattrs(cls, *attrs): | |
| def _iffattrs(self, other): | |
| for name in attrs: | |
| if not hasattr(self, name) or not hasattr(other, name): | |
| return False | |
| if getattr(self, name) != getattr(other, name): | |
| return False | |
| return True | |
| cls.__eq__ = _iffattrs | |
| class SampleClass(object): | |
| def __init__(self, name, age): | |
| self.name = name | |
| self.age = age | |
| iffattrs(SampleClass, "name", "age") | |
| yae = SampleClass("yae", 16) | |
| _yae = SampleClass("yae", 16) | |
| cath = SampleClass("cath", 16) | |
| print(yae == _yae) | |
| print(yae == cath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment