Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

difference between type(self) and self

0 votes
asked Jan 29, 2020 by anonymous
class C: 

    counter = 0
    
    def __init__(self): 
        type(self).counter += 1
x=C()
print(x.counter)
print(C.counter)
both the above print statement gives output 1 while if i use self.counter+=1 then the first print gives output 0 and second print gives 1, can anyone explain?

1 Answer

0 votes
answered Nov 2, 2023 by Cheng Thao (180 points)
type(self) gives you the class.  In your case, it's just the class C.

type(self).counter+=1 is the same as C.counter+=1

x = C()

x is an instance, which has its own copy of counter.

self.counter+=1 is making change to the instance copy of counter.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...