Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDavid Sampimon
12,026 PointsAdding new (undefined) attributes on class instances
I was playing around with classes in Python when I noticed I could add any random attribute to instances with dot notation. Even attributes not defined within __init__
.
For example:
class Dog():
# A class 'Dog' which only has one attribute 'name'
def __init__(self, name):
self.name = name
def __str__(self):
return f'Attributes: {self.__dict__}'
# Creating a dog named Oscar
oscar = Dog('Oscar')
# Adding a new attribute 'wings' that has not been defined in the class
oscar.wings = 2
# Printing the attributes of the class
print(oscar)
Prints out:
Attributes: {'name': 'Oscar', 'wings': 2}
What is the use of adding attributes to a class which are not defined? Is this not error-prone? Imagine that I thought in the above example that 'oscar' was an instance of class Bird (which has a wings attribute). Wouldnt it be better if I was notified that 'oscar' does not have an attribute 'wings'?
2 Answers
Steven Parker
231,269 PointsA fully developed program wouldn't need that kind of check, but you can easily add one during development if you think you need it:
if not hasattr(oscar, "wings"): # first, make sure it exists
raise AttributeError("object oscar has no wings attribute")
oscar.wings = 2 # THEN set it
David Sampimon
12,026 PointsOk, I am probably not understanding this right.
My question was more about potential mistakes when people use your code, not about simplicity.
I (mistakenly) thought that when you create a class, you define all of the class and instance attributes as part of the scope of the class and only there. By doing this, other people working on your code clearly understand what a valid 'Dog' is for example, and you can easily map the attributes to a database.
When you allow random attributes to be added to instances, I thought it would make things more unclear:
- You are not presented with an error when you try to add an non-existing attribute (e.g. trying to add wings to a dog)
- You can not derive from an instance which attributes are defined in the class.
But maybe I am concerned about a non-existing issue.
Steven Parker
231,269 PointsThis kind of issue can't happen when people use properly developed code, it can only happen if a mistake is made in writing the code.
Some development issues, like bad syntax, will cause an error when the program is run. But others, like this example, may cause the program to do the wrong thing but not generate an error. There are testing strategies used in development to help detect those kinds of issues which will be covered in later courses.
David Sampimon
12,026 PointsDavid Sampimon
12,026 PointsThanks Steven, but what is the use of adding attributes like this? Why would you even want to do that?
Steven Parker
231,269 PointsSteven Parker
231,269 PointsSeems simple and intuitive to me, how would you expect to do it?