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…
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…
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.