Skip to content

Instantly share code, notes, and snippets.

@zed
Created September 15, 2009 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/187588 to your computer and use it in GitHub Desktop.
Save zed/187588 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""Playing with pets.
http://stackoverflow.com/questions/1427479/managing-object-instances/1429344#1429344
"""
class Pet(object):
"""A pet with a name.
"""
def __new__(cls, name):
"""Create a pet with a `name`.
"""
return '<%s name="%s" xmlns="http://gist.github.com/187588"/>' % (
cls.__name__, name.replace('"', '\"'))
name2pet = {} # combined register of all pets
@classmethod
def get(cls, name):
"""Return a pet with `name`.
Try to get the pet registered by `name`
otherwise register a new pet and return it
"""
register = cls.name2pet
try: return register[name]
except KeyError:
pet = register[name] = cls(name) # no duplicates allowed
Pet.name2pet.setdefault(name, []).append(pet)
return pet
class Cat(Pet):
name2pet = {} # each class has its own registry
class Dog(Pet):
name2pet = {}
def test():
assert eval(repr(Cat("Teal'c"))) == Cat("Teal'c")
pets = [Pet('a'), Cat('a'), Dog('a'), Cat.get('a'), Dog.get('a')]
assert all('name="a"' in pet for pet in pets)
cat, dog = Cat.get('pet'), Dog.get('pet')
assert cat == '<Cat name="pet" xmlns="http://gist.github.com/187588"/>'
assert dog == '<Dog name="pet" xmlns="http://gist.github.com/187588"/>'
assert dog is not cat
assert dog != cat
assert all(v == [Cat(k), Dog(k)]
for k, v in Pet.name2pet.items()), Pet.name2pet
try: assert 0
except AssertionError:
return "OK"
raise AssertionError("Assertions must be enabled during the test")
if __name__=="__main__":
print test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment