Add new example: Subclass transitivity

This commit is contained in:
Satwik Kansal 2018-01-07 11:06:47 +05:30
parent c346b69be8
commit 0da5243425
1 changed files with 26 additions and 0 deletions

26
README.md vendored
View File

@ -1678,6 +1678,32 @@ SyntaxError: invalid syntax
---
### Subclass relationships
Suggested by @Lucas-C in [this](https://github.com/satwikkansal/wtfpython/issues/36) issue.
**Output:**
```py
>>> from collections import Hashable
>>> issubclass(list, object)
True
>>> issubclass(object, Hashable)
True
>>> issubclass(list, Hashable)
False
```
The Subclass relationships were expected to be transitive, right? (i.e. if `A` is a subclass of `B`, and `B` is a subclass of `C`, the `A` _should_ a subclass of `C`)
#### 💡 Explanation:
* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass.
* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey "`__hash__`" method in `cls` or anything it inherits from.
* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation.
* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/).
---
### Let's see if you can guess this?
Suggested by @PiaFraus in [this](https://github.com/satwikkansal/wtfPython/issues/9) issue.