New-Style Class Changes

New-style classes differ from classic classes in a number of ways, some of which are subtle but can impact existing 2.X code and coding styles. Here are some of the most prominent ways they differ:

Classes and types merged

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Classes are now types, and types are now classes. In fact, the two are essentially synonyms. The type(I) built-in returns the class an instance is made from, instead of a generic instance type, and is normally the same as I.__class__. Moreover, classes are instances of the type class, type may be subclassed to customize class creation, and all classes (and hence types) inherit from object.

Inheritance search order

Diamond patterns of multiple inheritance have a slightly different search order—roughly, they are searched across before up, and more breadth-first than depth-first.

Attribute fetch for built-ins

The __getattr__ and __getattribute__ methods are no longer run for attributes implicitly fetched by built-in operations. This means that they are not called for __X__ operator overloading method names—the search for such names begins at classes, not instances.

New advanced tools

New-style classes have a set of new class tools, including slots, properties, descriptors, and the __getattribute__ method. Most of these have very specific tool-building purposes.

We discussed the third of these changes briefly in a sidebar in Chapter 27, and we’ll revisit it in depth in the contexts of attribute management in Chapter 37 and privacy decorators in Chapter 38. Because the first and second of the changes just listed can break existing 2.X code, though, let’s explore these in more detail before moving on to new-style additions.