Repository: pydantic/pydantic

Issue:
__hash__() is squashed on subclass
### Checks

* [x] I added a descriptive title to this issue
* [x] I have searched (google, github) for similar issues and couldn't find anything
* [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug

# Bug

The following code worked in pydantic 1.7.3 (version info shown below), but fails with pydantic 1.8:

```py
from pydantic import BaseModel

class Foo(BaseModel):
    x: int

    # Failed attempt to fix; see below
    # __slots__ = ("__hash__",)

    def __hash__(self):
        return self.x ** 2

f = Foo(x=2)
assert hash(f) == 4

class Bar(Foo):
    y: float

b = Bar(x=2, y=1.1)

try:
    assert hash(b) == 4
except TypeError as e:
    # TypeError: unhashable type: 'Bar'
    print(e)
```
It seems like this code prevents the use of `Foo.__hash__` on `Bar` instances:
https://github.com/samuelcolvin/pydantic/blob/master/pydantic/main.py#L347

I tried to experiment with adding `"__hash__"` to `__slots__`, but an error is triggered in `ModelMetaclass.__new__`:
```
Traceback (most recent call last):
  File "bug.py", line 4, in <module>
    class Foo1(BaseModel):
  File "pydantic/main.py", line 352, in pydantic.main.ModelMetaclass.__new__
  File "/usr/lib/python3.8/abc.py", line 85, in __new__
    cls = super().__new__(mcls, name, bases, namespace, **kwargs)
ValueError: '__hash__' in __slots__ conflicts with class variable
```

I would expect that this continues to work as in 1.7.3, or that the documentation suggests how to avoid having these methods squashed.

----

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
Passing version:
```
$ python -c "import pydantic.utils; print(pydantic.utils.version_info())"
             pydantic version: 1.7.3
            pydantic compiled: True
                 install path: /home/khaeru/.local/lib/python3.8/site-packages/pydantic
               python version: 3.8.6 (default, Jan 27 2021, 15:42:20)  [GCC 10.2.0]
                     platform: Linux-5.8.0-43-generic-x86_64-with-glibc2.32
     optional deps. installed: ['typing-extensions']
```

Failing version:
```
$ python -c "import pydantic.utils; print(pydantic.utils.version_info())"
             pydantic version: 1.8
            pydantic compiled: True
                 install path: /home/khaeru/.local/lib/python3.8/site-packages/pydantic
               python version: 3.8.6 (default, Jan 27 2021, 15:42:20)  [GCC 10.2.0]
                     platform: Linux-5.8.0-43-generic-x86_64-with-glibc2.32
     optional deps. installed: ['typing-extensions']
```


Discussion:

Resolving patch:
diff --git a/pydantic/main.py b/pydantic/main.py
--- a/pydantic/main.py
+++ b/pydantic/main.py
@@ -231,6 +231,7 @@ def __new__(mcs, name, bases, namespace, **kwargs):  # noqa C901
         slots: SetStr = namespace.get('__slots__', ())
         slots = {slots} if isinstance(slots, str) else set(slots)
         class_vars: SetStr = set()
+        hash_func: Optional[Callable[[Any], int]] = None
 
         for base in reversed(bases):
             if _is_base_model_class_defined and issubclass(base, BaseModel) and base != BaseModel:
@@ -241,6 +242,7 @@ def __new__(mcs, name, bases, namespace, **kwargs):  # noqa C901
                 post_root_validators += base.__post_root_validators__
                 private_attributes.update(base.__private_attributes__)
                 class_vars.update(base.__class_vars__)
+                hash_func = base.__hash__
 
         config_kwargs = {key: kwargs.pop(key) for key in kwargs.keys() & BaseConfig.__dict__.keys()}
         config_from_namespace = namespace.get('Config')
@@ -332,6 +334,9 @@ def is_untouched(v: Any) -> bool:
             json_encoder = pydantic_encoder
         pre_rv_new, post_rv_new = extract_root_validators(namespace)
 
+        if hash_func is None:
+            hash_func = generate_hash_function(config.frozen)
+
         exclude_from_namespace = fields | private_attributes.keys() | {'__slots__'}
         new_namespace = {
             '__config__': config,
@@ -344,7 +349,7 @@ def is_untouched(v: Any) -> bool:
             '__custom_root_type__': _custom_root_type,
             '__private_attributes__': private_attributes,
             '__slots__': slots | private_attributes.keys(),
-            '__hash__': generate_hash_function(config.frozen),
+            '__hash__': hash_func,
             '__class_vars__': class_vars,
             **{n: v for n, v in namespace.items() if n not in exclude_from_namespace},
         }


Test patch:
diff --git a/tests/test_main.py b/tests/test_main.py
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -395,6 +395,27 @@ class TestModel(BaseModel):
     assert "unhashable type: 'TestModel'" in exc_info.value.args[0]
 
 
+def test_with_declared_hash():
+    class Foo(BaseModel):
+        x: int
+
+        def __hash__(self):
+            return self.x ** 2
+
+    class Bar(Foo):
+        y: int
+
+        def __hash__(self):
+            return self.y ** 3
+
+    class Buz(Bar):
+        z: int
+
+    assert hash(Foo(x=2)) == 4
+    assert hash(Bar(x=2, y=3)) == 27
+    assert hash(Buz(x=2, y=3, z=4)) == 27
+
+
 def test_frozen_with_hashable_fields_are_hashable():
     class TestModel(BaseModel):
         a: int = 10