educative.io

Class references before object instantiation

Could anyone help me to understand why does a class consists of (4 + 1) references before even creating an object for it in Python?

from sys import getrefcount
from gc import get_referrers
class A:
… pass

get_referrers(A)
[<attribute ‘dict’ of ‘A’ objects>, <attribute ‘weakref’ of ‘A’ objects>, (<class ‘main.A’>, <class ‘object’>), {‘name’: ‘main’, ‘doc’: None, ‘package’: None, ‘loader’: <class ‘_frozen_importlib.BuiltinImporter’>, ‘spec’: None, ‘annotations’: {}, ‘builtins’: <module ‘builtins’ (built-in)>, ‘getrefcount’: , ‘get_referrers’: , ‘A’: <class ‘main.A’>}]

getrefcount(A)
5

I am only aware that one reference is passed when I am calling get_referrers/getrefcount method.
Please bridge the gap.

Could anyone help me to understand why does a class consists of (4 + 1) references before even creating an object for it in Python?

Type your question above this line.

Course: https://www.educative.io/collection/10370001/6201068373409792
Lesson: https://www.educative.io/collection/page/10370001/6201068373409792/5682521335398400

Hello @learn

sys.getrefcount() tells us the reference count of an object. For instance, sys.getrefcount(2) will tell us how many things or objects in Python currently have the integer value 2. It should be noted that reference count returned is one more than the total reference count. This is because sys.getrefcount() creates one additional internal reference as well. So if there are 4 references for an object, the returned value would be 5.

Now even if object has not been created yet, there might be other things or objects inside Python that would have an object or method of type A. As per your provided output, those are 4 and returned value is 5 due to the one additional internal reference created.

Hope this helps!