Skip to content

Commit 9ea7ab0

Browse files
committed
New example: The chicken-egg problem
Closes satwikkansal#101
1 parent 72e39d3 commit 9ea7ab0

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -730,6 +730,54 @@ Even when the values of `x` were different in every iteration prior to appending
730730
731731
---
732732
733+
### ▶ The chicken-egg problem ^
734+
735+
1\.
736+
```py
737+
>>> isinstance(3, int)
738+
True
739+
>>> isinstance(type, object)
740+
True
741+
>>> isinstance(object, type)
742+
True
743+
```
744+
745+
2\. So which is the ultimate, base class? And wait, there's more to the confusion
746+
747+
```py
748+
>>> class A: pass
749+
>>> isinstance(A, A)
750+
False
751+
>>> isinstance(type, type)
752+
True
753+
>>> isinstance(object, object)
754+
True
755+
```
756+
757+
3\.
758+
759+
```py
760+
>>> issubclass(int, object)
761+
True
762+
>>> issubclass(type, object)
763+
True
764+
>>> issubclass(object, type)
765+
False
766+
```
767+
768+
769+
#### 💡 Explanation
770+
771+
- `type` is a [metaclass](https://realpython.com/python-metaclasses/) in Python.
772+
- **Everything** is an `object` in Python, which includes classes as well as their objects (instances).
773+
- class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`.
774+
- There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking these relationships (`issubclass` and `isinstance`) in terms of Python classes. The relationship between `object` and `type` can't be reproduced in pure python. To be more precise the following relationships can't be reproduced in pure Python,
775+
+ class A is instance of class B, and class B is an instance of class A.
776+
+ class A is an instance of itself.
777+
- These relationships between `object` and `type` (both being instances of eachother as well as themselves) exist in Python because of "cheating" at implementation level.
778+
779+
---
780+
733781
### ▶ `is not ...` is not `is (not ...)`
734782
735783
```py

0 commit comments

Comments
 (0)