10 Fundamentals of objects

 

This chapter covers

  • Inspecting objects
  • Illustrating an object’s lifecycle
  • Copying an object
  • Resolving a variable: the LEGB rule
  • Understanding an object’s callability

Objects are everywhere in Python, as Python is an object-oriented programming (OOP) language by design. We work with objects constantly in our applications. Thus, it’s important to know the fundamentals of using objects, particularly instance objects of a custom class, as they’re the most prevalent data model in applications. In a function, for example, we expect that users may send different types of data, and we can add this flexibility by handling applicable data types accordingly. As another example, copying an object is necessary when we have a working copy to update while keeping the original object intact in case we need to revert our update. In this chapter, I’ll cover the fundamentals of objects. Certainly, this chapter isn’t intended to be exhaustive, as everything is an object in Python, and I can’t cover all the aspects of how objects are used. Another thing to note is that some sections address a specific problem (section 10.4, for example, is about changing a variable in a different scope), but I’ll use addressing the specific problem to cover a more general topic (such as the variable lookup order).

10.1 How do I inspect an object’s type to improve code flexibility?

10.1.1 Checking an object’s type using type

10.1.2 Checking an object’s type using isinstance

10.1.3 Checking an object’s type generically

10.1.4 Discussion

10.1.5 Challenge

10.2 What’s the lifecycle of instance objects?

10.2.1 Instantiating an object

10.2.2 Being active in applicable namespaces

10.2.3 Tracking reference counts

10.2.4 Destructing the object

10.2.5 Discussion

10.2.6 Challenge

10.3 How do I copy an object?

10.3.1 Creating a (shallow) copy

10.3.3 Creating a deep copy