Working with fields

Working with fields#

To use a field, you can simply refer to it on an object. Here’s an example where we add a field to an instance of our Empty class:

Notice that we’ve only set the a field on the object e, and instance of Empty. Other instances don’t have it. Edit the code above to explore that idea!

Notice that we’ve only set the a field on the object e, and instance of Empty. Other instances don’t have it. Edit the code above to explore that idea! If you try to access an uninitialized field, you’ll get an AttributeError:

A common and useful idiom is to set fields on an object in the constructor. Here’s an example of a class that acts a bit like a 2-tuple: it holds two things.

A confusing, but common idiom is to use the same name for arguments to a constructor and the field they’ll be setting, as in: