0

I have written program below without using the __init__ purposely.

class testing:
     skills=[]
     def addSkill(self,skill):
         self.skills.append(skill)
john=testing()
betty=testing()
john.addSkill("FOOTBALL")
betty.addSkill("TENNIS")
print john.skills

Above code gives the output as ['FOOTBALL', 'TENNIS'].

Now I am not able to understand as why python is appending to the same variable skills even when I have created two different instances and used self (self.skills.append(skill)) to append to particular instance only.

Although if I use __init__ and then declare the skills set inside it, then my code is working fine.

martineau
  • 119,623
  • 25
  • 170
  • 301
Code_maniac
  • 49
  • 1
  • 7
  • because `skills` is a class attribute, not an instance attribute; *it's shared among instances*. – Dimitris Fasarakis Hilliard May 27 '17 at 14:32
  • @JimFasarakisHilliard thanks for the answer. But then what is the use of self here. – Code_maniac May 27 '17 at 14:37
  • `self` represents the instance. Through the instance you can access both instance attributes and class ones. You're accessing a class attribute through `self` and modifying it. – Dimitris Fasarakis Hilliard May 27 '17 at 14:39
  • @JimFasarakisHilliard then how come the below code printing JOHN instead of BETTY, as class variable name is assigned a value BETTY after the JOHN i.e the value must be overwritten during the second assignment. `class testing: skills=[] name="" def addSkill(self,skill): self.skills.append(skill) john=testing() betty=testing() john.name="JOHN" betty.name="BETTY" print john.name` – Code_maniac May 27 '17 at 14:59

0 Answers0