5.9.2 Advantages of Class-Based Views

The key advantages and disadvantages of CBVs over function views are exactly the same advantages and disadvantages that classes and objects have over functions: encapsulating data and behavior is typically more intuitive but can easily grow in complexity, which comes at the cost of functional purity.

A staple of object-oriented programming (OOP) is the use of instance variables, typically referred to as attributes in Python. For instance, we can usually better adhere to DRY in classes by defining important values as attributes. In PostList, we replace the string in render() with an attribute (which contains the same value), as shown in Example 5.63.

Example 5.63: Project Code

blog/views.py in ac3db8b26b

Get Django Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.