mirror of
https://github.com/satwikkansal/wtfpython
synced 2024-11-24 20:14:23 +01:00
Add new example: Subclass transitivity
This commit is contained in:
parent
c346b69be8
commit
0da5243425
26
README.md
vendored
26
README.md
vendored
@ -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.
|
||||
|
Loading…
Reference in New Issue
Block a user