0

This code is written in Object Oriented Programming in Python.How to count reference variables in this program.I tried printing the ID's of these Objects but it didn't helped me.

class Computer:
        def __init__(self):
            self.no_of_legs=4
            self.glass_top=None
            self.wooden_top=None
Obj1=Computer()
Obj2=Computer()
Obj3=Obj2
Obj2=Obj1
  • Assuming that those four final lines aren't supposed to be indented (which would be a syntax error), you have three variables, referring to two distinct objects. `Obj1` and `Obj2` refer to one of them, `Obj3` is the only remaining reference to the other one originally held in `Obj2`. – jasonharper Jul 20 '20 at 15:03
  • Why do you need counting references? – Jan Stránský Jul 20 '20 at 15:14
  • @JanStránský I want to count reference variables to know the concept of reference variables and also it is a question in one of the quiz. – Anudeep Kosuri Jul 20 '20 at 15:55
  • @jasonharper syntax error came due to copy,paste of code from compiler directly and i have changed it. Can you explain me the same by counting the reference variables. I am getting confused while counting the reference variables – Anudeep Kosuri Jul 20 '20 at 15:59
  • possible [duplicate](https://stackoverflow.com/questions/10874499/understanding-reference-count-of-class-variable) using [sys.getrefcount](https://docs.python.org/3/library/sys.html#sys.getrefcount) – Jan Stránský Jul 20 '20 at 16:26

1 Answers1

0

You can use sys.getrefcount:

from sys import getrefcount
class Computer:
    def __init__(self):
        self.no_of_legs=4
        self.glass_top=None
        self.wooden_top=None
Obj1=Computer()
Obj2=Computer()
print(getrefcount(Obj1)) # 2
print(getrefcount(Obj2)) # 2
Obj3=Obj2
Obj2=Obj1
print(getrefcount(Obj1)) # 3
print(getrefcount(Obj2)) # 3
print(getrefcount(Obj3)) # 2
Jan Stránský
  • 1,671
  • 1
  • 11
  • 15