Search code examples
pythonclasshashsetgetattr

Python: no attribue __hash__


Instances of PackOfPersons have a __getattr__() function that, for example: PackOfPersons.say_name() will call Person.say_name() for Person instances inside PackOfPersons.person_objects().

class Person:
    def __init__(self, name):
        self.name = name

    def say_name(self):
        print 'my name is', self.name

    def add_to_set(self):
        PersonObjectSet.add(self)

class PackOfPersons:
    def __init__(self, person_objects):
        self.person_objects = person_objects

    def __getattr__(self, item):
        def _group_helper(*args, **kwargs):
            for person in self.person_objects:
                getattr(person, item)(*args, **kwargs)

        return _group_helper


PersonObjectSet = set([])
PackObjectSet = set([])

a = Person("Albert")
b = Person("Bernie")
c = Person("Catherine")
p = PackOfPersons([a, b, c])
p.say_name()
PackObjectSet.add(p)

The last line throws an error which is traced back to:

line 18, in _group_helper
    getattr(person, item)(*args, **kwargs)
AttributeError: Person instance has no attribute '__hash__'

How do I work around this issue?


Solution

  • Solved the issue by declaring class PackOfPersons(object):