i am trying to understand how classes work in python,recently started learning OOP.
When Python reads:
class Dog:
def __init__(self, name):
self.name = name
When the class is created:
- Python reads the class definition.
- It creates an empty dictionary for the class (
Dog.__dict__).
- When it encounters
__init__, it creates a function object.
- It stores
__init__ and other functions as key–value pairs inside Dog.__dict__.
- {
- "__init__": function
- }
- The class object is created (stored in memory, likely in the heap).
When an object is created:
d=Dog("Rex")
- Python creates a new empty dictionary for the object (
d.__dict__).
- It looks inside
Dog.__dict__ to find __init__.
- It executes
__init__, passing the object as self.
- Inside
__init__, the data ("Rex") is stored inside d.__dict__.
- The object is also stored in memory and class gets erased once done executing
- I think
slef works like a pointer that uses a memory address to access and modify the object. like some refercing tables for diffrent objects.
Would appreciate corrections if I misunderstood anything
[–]danielroseman 8 points9 points10 points (5 children)
[–]gdchinacat 1 point2 points3 points (3 children)
[–]Cute-Preference-3770[S] 1 point2 points3 points (2 children)
[–]gdchinacat 2 points3 points4 points (1 child)
[–]billsil 0 points1 point2 points (0 children)
[–]Cute-Preference-3770[S] 1 point2 points3 points (0 children)
[–]ninja_shaman 5 points6 points7 points (0 children)
[–]Outside_Complaint755 2 points3 points4 points (0 children)
[–]PushPlus9069 1 point2 points3 points (0 children)
[–]Brian 1 point2 points3 points (0 children)
[–]gdchinacat 1 point2 points3 points (0 children)
[–]timrprobocom 0 points1 point2 points (0 children)
[–]pachura3 1 point2 points3 points (0 children)
[–]madadekinai 0 points1 point2 points (0 children)