Attributes and Behaviors

Learn about attributes and behaviors of the class and their representation in class diagrams.

We now have a grasp of some basic object-oriented terminology. Objects are instances of classes that can be associated with each other. A class instance is a specific object with its own set of data and behaviors; a specific orange on the table in front of us is said to be an instance of the general class of oranges. The orange has a state, for example, ripe or raw; we implement the state of an object via the values of specific attributes. An orange also has behaviors. By themselves, oranges are generally passive. State changes are imposed on them. Let’s dive into the meaning of those two words, state and behaviors.

Data describes object state

Let’s start with data. Data represents the individual characteristics of a certain object; its current state. A class can define specific sets of characteristics that are part of all objects that are members of that class. Any specific object can have different data values for the given characteristics. For example, the three oranges on our table (if we haven’t eaten any) could each weigh a different amount. The Orange class could have a weight attribute to represent that datum. All instances of the Orange class have a weight attribute, but each orange has a different value for this attribute. Attributes don’t have to be unique, though; any two oranges may weigh the same amount.

Attributes are frequently referred to as members or properties. Some authors suggest that the terms have different meanings, usually that attributes are settable while properties are read-only. A Python property can be defined as read-only, but the value will be based on attribute values that are—ultimately—writable, making the concept of read-only rather pointless; throughout this course, we’ll see these two terms used interchangeably. In addition, we’ll discuss later that the property keyword has a special meaning in Python for a particular kind of attribute.

Instance variable

In Python, we can also call an attribute an instance variable. This can help clarify the way attributes work. They are variables with unique values for each instance of a class. Python has other kinds of attributes, but we’ll focus on the most common kind to get started.

In our fruit inventory application, the fruit farmer may want to know what orchard the Orange came from, when it was picked, and how much it weighs. They might also want to keep track of where each Basket is stored. Apples might have a color attribute, and barrels might come in different sizes.

Some of these properties may also belong to multiple classes (we may want to know when apples are picked, too), but for this first example, let’s just add a few different attributes to our class diagram:

Get hands-on with 1200+ tech skills courses.