FAQ: Learn Python: Classes - Instance Variables

This community-built FAQ covers the “Instance Variables” exercise from the lesson “Learn Python: Classes”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise Instance Variables

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

2 posts were split to a new topic: What is the difference between a class variable and instance variable?

class Store:
  pass

alternative_rocks = Store()
isabelles_ices = Store()

alternative_rocks= "Alternative Rocks"
isabelles_ices = "Isabelle's Ices"

working_string = "{} {}".format(alternative_rocks, isabelles_ices)
print(working_string)

Without assigning(?) the instances variables, it just works fine. Why do we have to assign the instance variable for this lesson??

2 Likes

How do we know what is class variable and what is instance variable??
For the previous lesson, Instance Variables (https://www.codecademy.com/courses/learn-python-3/lessons/data-types/exercises/instance-variables), the instance variable, fake_key, just works fine without throwing an ‘AttributeError’ message in the terminal. (What I meant for “it works fine” is that when executing the last line, print(working_string) it didn’t throw an error.)

class FakeDict:
  pass

fake_dict1 = FakeDict()
fake_dict2 = FakeDict()

fake_dict1.fake_key = "This works!"
fake_dict2.fake_key = "This too!"

# Let's join the two strings together!
working_string = "{} {}".format(fake_dict1.fake_key, fake_dict2.fake_key)
print(working_string)
# prints "This works! This too!"

So what confuses me is this sentence from the lecture note of Attribute Function below.

“”“If we attempt to access an attribute that is neither a class variable nor an instance variable of the object Python will throw an AttributeError .”""

class NoCustomAttributes:
  pass

attributeless = NoCustomAttributes()

try:
  attributeless.fake_attribute
except AttributeError:
  print("This text gets printed!")

# prints "This text gets printed!"

How are these two codes, specifically the two instance variables (.fake_key, .fake_attribute) different? Those are instance variables, assumed that those are not defined in each class, and one is working fine without error but the latter one is not. This is very confusing…

1 Like

I am a little bit confused about instance variables.
if we don’t have some variables in our class definition then can we add them using a instance variable?
Or Do we use instance variable only to add in init method???
Someone please explain this…:blush:

We do not need to define all of our class variables in the class definition? We can dynamically add attributes?

Yes, but only to an instance. It does not become a common instance variable across all instances.

>>> class Foo:
	pass

>>> foo = Foo()
>>> foo.attr = 42
>>> foo.attr
42
>>> bar = Foo()
>>> bar.attr
Traceback (most recent call last):
  File "<pyshell#280>", line 1, in <module>
    bar.attr
AttributeError: 'Foo' object has no attribute 'attr'
>>> 
>>> Foo.attr
Traceback (most recent call last):
  File "<pyshell#278>", line 1, in <module>
    Foo.attr
AttributeError: type object 'Foo' has no attribute 'attr'
>>> 

how to check the available attributes of any class or object?

What would be the purpose?

if i am interacting with pre existing object and i am not sure what attributes does it have or not to work with or to add new attributes.
actually i am not friendly with this object thing but this thought just came to my mind, so i asked.

for example: if am working with list a and i don’t know what attributes does it have. Instead of guessing i would just check for those attributes.

One way would be to look at the directory of attributes on the parent class…

>>> dir(list)

We can also read the docstring of it or any of the attributes that have one…

>>> help(list)

And the one place we should never skip is the documentation online…

1 Like

Hello, didn’t quite get why we are using init method. what’s the difference between class with Init and without it?

A class without an __init__() method would have no unique object instance attributes.

Can the instance attributes be named randomly?

If you mean in any order, yes. The only requirement is that if one attribute refers to another, that attribute must follow the one it references.

I think this whole instance variable thing is pretty sweet. I can’t wait to use it, but one thing confuses me. Why doesn’t it work on the str class?

class Store:

  pass

alternative_rocks = Store()

isabelles_ices = Store()

alternative_rocks.store_name = "Alternative Rocks"

isabelles_ices.store_name = "Isabelle's Ices"

print(isabelles_ices.store_name)

print(type(isabelles_ices))

someName = "thisname"

print(type(someName))

someName.whatever = "I want!"

print(someName.whatever)
Isabelle's Ices
<class '__main__.Store'>
<class 'str'>
Traceback (most recent call last):
  File "script.py", line 14, in <module>
    someName.whatever = "I want!"
AttributeError: 'str' object has no attribute 'whatever'

And thus ends the conversation.

I’m not sure if I understand.

class Store:
  pass

store1 = Store()
print(type(store1))
store1.whatever = "I want!"
print(store1.whatever)

Output:

<class '__main__.Store'>
I want!

…unless…

class yPythonJoke:
   pass

No, not a joke. Reality. We can add attributes to a class instance publicly. They will however only belong to that instance.

>>> class Foo:
	pass

>>> foo = Foo()
>>> def add_bar():
	return 'bar'

>>> foo.add_bar = add_bar
>>> foo.add_bar()
'bar'
>>> 
1 Like

I may be confused. :slight_smile:

In my original code, isn’t someName an instance of the str class?

If it is, why am I unable to add attributes to the instance?