Is there really a need to use instance variables?

Are there cases where instance variables are required or preferred?
In this module: https://www.codecademy.com/courses/learn-python-3/lessons/data-types/exercises/instance-variables
The code they are wanting us to make looks like this:

class Store:
  pass
alternative_rocks = Store()
isabelles_ices = Store()
alternative_rocks.store_name = "Alternative Rocks"
isabelles_ices.store_name = "Isabelle's Ices"

But, isn’t it more efficient to just do this:

class Store:
  def __init__(self, store_name):
    self.store_name = store_name
alternative_rocks = Store("Alternative Rocks")
isabelles_ices = Store("Isabelle's Ices")
print(alternative_rocks.store_name)
print(isabelles_ices.store_name)

Please help!

If each and every instance must have a store_name variable which is known ahead of time then you’re right that it would probably be better that way. Based on where this lesson sits in the course I think they’re just pointing out that you can bind variables to individual instances without affecting any other instances; it looks more like an example than a suggested method.

4 Likes

May be worth noting that both of your examples are of instance variables. The only difference is when/how they are defined, and as @tgrtim pointed out whether they are required of all instances.

4 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.