Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Khác biệt giữa old-style và new-style class trong Python

Chỉ tồn tại trong Python 2.x. Python 3.x chỉ có new-style class.

Old-style class (Classic)

class OldSpam:
    pass

OldSpam.__bases__  # ()

Không có built-in type làm base class.

New-style class

class NewSpam(object):
    pass

NewSpam.__bases__  # (,)

class IntSpam(int):
    pass

IntSpam.__bases__  # (,)
IntSpam.__bases__[0].__bases__  # (,) - int kế thừa object

Kế thừa trực tiếp hoặc gián tiếp từ object.

Ưu điểm new-style class

  • Hỗ trợ descriptors: classmethod, staticmethod, property.
  • MRO (Method Resolution Order) chính xác cho multiple inheritance.
  • super() hoạt động đúng.
  • Slot (__slots__) tiết kiệm memory.
  • Meta-class hỗ trợ đầy đủ.

Python 3.x

class Foo:
    pass  # Tự động kế thừa object

Foo.__bases__  # (,)

Không cần viết (object).