Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 7 · Object Attributes and Methods

Object Attributes and Methods

On this pageDefine the BookUse Attributes and MethodsExample: Temperature ConversionCoding Challenge: Initialize Movie Class with __init__Reference

The previous section used x, a value stored on a class. An instance attribute instead stores information for one object. A method is a function defined in a class that can work with an object’s data [1]. A book, for example, can store its title, author and year, and provide a method that returns a description.

Figure 13 shows the Book class using UML notation. The middle compartment lists attributes; the bottom lists operations. A + marks a public member, a colon introduces its type, and parentheses distinguish an operation from an attribute. Here, str means text and int means an integer.

Book+title: str+author: str+year: int+summarize(): str

Define the Book

We use def to define a method, just as we define a function. Its first parameter, conventionally named self, receives the object on which the method is called. Python calls the special method __init__ after creating an instance; here it stores the supplied starting values. The next section examines this initialization step in detail.

class Book:
    def __init__(self, title, author, year):
        self.title = title
        self.author = author
        self.year = year

    def summarize(self):
        return f"'{self.title}' by {self.author} ({self.year})"
Listing 276 — Define the Book

The assignments attach title, author and year to the object received as self. The summarize method reads those attributes and uses an f-string to build a description; expressions inside {} supply the values. return sends that text back to the caller. Defining this class produces no visible output.

Use Attributes and Methods

Run the class definition above, then create two books. Treat the titles, authors and years as sample inputs. Read an attribute with a dot, as in b1.title; add parentheses to call a method, as in b1.summarize().

b1 = Book("The Bhagavad Gita", "Vyasa", -400)
b2 = Book("Python Crash Course", "Eric Matthes", 2016)
print(b1.title)
print(b1.summarize())
print(b2.summarize())
Listing 277 — Use Attributes and Methods

Output

The Bhagavad Gita
'The Bhagavad Gita' by Vyasa (-400)
'Python Crash Course' by Eric Matthes (2016)

The first line reads b1’s title directly. Each method call then uses the attributes of the object before the dot: b1 for the first description and b2 for the second. The method returns text; print displays it. This is how one method definition works with different objects without copying its logic.

Example: Temperature Conversion

The same pattern can represent a measurement. Temperature stores a Celsius value in celsius; its to_fahrenheit() method converts that value using Celsius × 9/5 + 32. In the following UML class diagram, the attribute has no stated type and the operation returns a float, a floating-point number.

Temperature+celsius+to_fahrenheit(): float

Predict the two results, then run this complete example:

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def to_fahrenheit(self):
        return self.celsius * 9/5 + 32

temp1 = Temperature(25)
temp2 = Temperature(49)
print(f"{temp1.celsius}°C is {temp1.to_fahrenheit()}°F")
print(f"{temp2.celsius}°C is {temp2.to_fahrenheit()}°F")
Listing 278 — Example: Temperature Conversion
Check your prediction

Output

25°C is 77.0°F
49°C is 120.2°F

Each method call reads that object’s Celsius value, multiplies it by 9/5 and adds 32. The surrounding f-string combines the original measurement with the returned result.

Try it: replace 25 with 0 when creating temp1. Predict the Fahrenheit value, run the example and explain the change.

Coding Challenge: Initialize Movie Class with __init__

Use Book as a model to create a Movie class with title, director and year attributes. Create objects with the sample inputs Inception / Christopher Nolan / 2010 and Spirited Away / Hayao Miyazaki / 2001. Print the first movie’s title and year, then the second movie’s title and director.

Target output for your solution

Inception
2010
Spirited Away
Hayao Miyazaki

These examples used __init__ to give each object its starting data. We will now look more closely at when Python calls it and how self identifies the object being initialized.

Reference

  1. Python Software Foundation. Classes: instance objects and method objects.