Skip to content

Instantly share code, notes, and snippets.

@tomoemon
Created November 5, 2015 09:38
Show Gist options
  • Save tomoemon/983e5c9477ecc3ec2a92 to your computer and use it in GitHub Desktop.
Save tomoemon/983e5c9477ecc3ec2a92 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
class Case(object):
__slots__ = []
def __init__(self, *args, **kwargs):
super_setattr = super(Case, self).__setattr__
slots = self.__slots__[:]
for slot, arg in zip(self.__slots__, args):
slots.remove(slot)
super_setattr(slot, arg)
for key, value in kwargs.items():
if key in self.__slots__:
super_setattr(key, value)
slots.remove(key)
for slot in slots:
super_setattr(slot, None)
def __setattr__(self, key, value):
raise AttributeError("cannot update the attribute of Case instance")
def __str__(self):
return self.__class__.__name__ + "(" + \
", ".join([s + "=" + str(getattr(self, s)) for s in self.__slots__]) + \
")"
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return isinstance(other, self.__class__) and \
not bool([True for s in self.__slots__ if getattr(self, s) != getattr(other, s)])
def __ne__(self, other):
return not self.__eq__(other)
def __iter__(self):
for slot in self.__slots__:
yield getattr(self, slot)
def __hash__(self):
return hash(tuple(getattr(self, s) for s in self.__slots__))
def copy(self, **kwargs):
new_case = self.__class__(*[getattr(self, s) for s in self.__slots__])
super_setattr = super(Case, new_case).__setattr__
for key, value in kwargs.items():
super_setattr(key, value)
return new_case
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment