0

Can anyone tell why, why the length of my instance variable( with type set) do not work the way as I though.

When I called a.addToSet("xx"), I thought the value of len(b.aSet) and len(ExampleClass.aSet) should return zero, so as a.aInt be 100 and rest be 0, while the console print the 1 for all the three instance.

Many thanks

==========================

Let's say, we have a class called ExampleClass with two variable: aSet and aInt.

class ExampleClass():
    aSet = set()
    aInt = 0
    def addToSet(self,aValue):
        self.aSet.add(aValue)

a=ExampleClass()
b=ExampleClass()
a.addToSet("xx")
a.aInt=100

print len(a.aSet)
print len(b.aSet)
print len(ExampleClass.aSet)
print a.aInt
print b.aInt
print ExampleClass.aInt

OUTPUT

1

1

1

100

0

0

Keyleo
  • 33
  • 6
  • Briefly: you created a class variable, not instance variables. – TigerhawkT3 May 31 '16 at 10:00
  • And see [here](http://stackoverflow.com/questions/8959097/what-is-the-difference-between-class-and-instance-variables-in-python) as well. – TigerhawkT3 May 31 '16 at 10:02
  • Sorry for duplicate, I have one more question, does python distinguish the simple date type and complex type? cause as the result showed, the aInt works just like the instance variable. – Keyleo May 31 '16 at 10:09
  • What do you mean by simple and complex? – TigerhawkT3 May 31 '16 at 10:10
  • just like primitive data types (int, float, etc), and non primitive data types(String, user defined Class) in Java. Which act difference way ( when pass into the method as parameter. – Keyleo May 31 '16 at 10:17
  • [Everything is an object in Python](http://stackoverflow.com/questions/26294953/how-does-everything-is-an-object-even-work). Just watch out for which ones are mutable or immutable, what's considered truthy and falsey, and so on. Python is [pass-by-reference](http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference). – TigerhawkT3 May 31 '16 at 10:23
  • Thank you very much – Keyleo May 31 '16 at 14:05

0 Answers0