Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created September 22, 2011 14:03
Show Gist options
  • Select an option

  • Save pasberth/1234844 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1234844 to your computer and use it in GitHub Desktop.
Python版の iffattrs
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