Câu hỏi phỏng vấn Python
Câu hỏi

What is the difference between old s...

Câu trả lời

The difference between old-style and new-style classes in Python primarily revolves around the inheritance model and the capabilities associated with each style.

Old-Style Classes

Old-style classes, also known as classic classes, were the only type of class available in Python until version 2.2. These classes do not inherit from any built-in type explicitly. In Python 2.x, a class defined without specifying a base class automatically becomes an old-style class. For example:

python Copy
class OldClass:
    pass

In old-style classes, the class and type of an instance are distinct. For instance, if x is an instance of an old-style class, type(x) would return a generic <type 'instance'>, not the specific class x belongs to[1][2][6].

New-Style Classes

Introduced in Python 2.2, new-style classes were designed to unify the concepts of type and class, meaning that a class is itself an instance of a type, and thus, they inherit from the built-in object type or another new-style class. This change was aimed at providing a more consistent object model and adding capabilities such as descriptors, metaclasses, and properties. A new-style class is defined by explicitly inheriting from object or another new-style class:

python Copy
class NewClass(object):
    pass

In new-style classes, the type of an instance is the class itself. For example, type(x) for an instance x of a new-style class would return NewClass, the actual class of x[1][2][3][4][5][6].

Key Differences

  1. Inheritance and Type System: New-style classes integrate with Python's type system, allowing for features like multiple inheritance and metaclasses more effectively. Old-style classes are more limited in this regard[1][2][3].

  2. Method Resolution Order (MRO): New-style classes use a more pred...

senior

senior

Gợi ý câu hỏi phỏng vấn

junior

What are the rules for local and global variables in Python?

middle

What is introspection/reflection and does Python support it?

expert

Is there a simple, elegant way to define singletons?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào