-1

I am looking for a way to call magic methods on class instances. In my case, I want to call hash on class based on properties. I found solution with metaclass, but I cannot access class properties from metaclass's method.

class X(type):
    @classmethod
    def __hash__(cls):
        return hash(cls.x)
class Y(metaclass=X):
        x = (1, 2, 3)
assert hash(Y) == hash((1, 2, 3))

I found just this thread: Defining magic methods on classes

Patrik Valkovič
  • 706
  • 7
  • 26
  • "but I cannot access class properties from metaclass's method" - what? Sure you can. – user2357112 Aug 15 '17 at 18:21
  • 2
    Why do you want to override the hashing of class objects? You're now obliged to implement the `__eq__` too. – wim Aug 15 '17 at 18:24

1 Answers1

2

Take the @classmethod off.

class X(type):
    def __hash__(self):
        return hash(self.x)
class Y(metaclass=X):
        x = (1, 2, 3)
assert hash(Y) == hash((1, 2, 3))

You want __hash__ to receive Y, which is an instance of X. You don't want it to receive X.

user2357112
  • 260,549
  • 28
  • 431
  • 505