class MemberCounter:
        members = 0
        def init(self):
            MemberCounter.members += 1

# m1 = MemberCounter()
# m1.init()
# MemberCounter.members
-> 1

# m2 = MemberCounter()
# m2.init()
# MemberCounter.members
-> 2

# m1.members
-> 2

-> 2

# m1.members = 'Two'
# m1.members
-> 'Two'

# m2.members
-> 2

In the above code how is it that in the upper portion m1 and m2 are sharing the same members variable but after I re-assign m1 to 'Two' and are suddenly two different variables? Also, what is init?

Edited by Dani: Formatting fixed

4 Years
Discussion Span
Last Post by lewashby

You are printing separate variables. MemberCounter.members is different from m1.members="Two". Print the id() of each, which will show that they all occupy different memory locations. You might also want to study up on the difference between class objects/attributes and instance objects/attributes Click Here Sometimes you are printing an instance object and sometimes you are printing a class object, which are different variables even though they have the same name. m2 does not have an instance object named "members" so it prints the class object. If you created one
it would print that instead, and
MemberCounter.members will always print the class object.

Edited by woooee

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.