Showing posts with label oop. Show all posts
Showing posts with label oop. Show all posts

Thursday, June 25, 2009

ไก่กับไข่ใน python OOP

วันนี้นั่งทำความเข้าใจกับ OOP ใน python
เนื่องจากไปเห็นว่า BaseModel ของ django มัน extend type
ก็เลยสงสัยว่าอะไรคือ object อะไรคือ type


# In Python, the __class__ attribute points to the type of an object

In [1]: object.__class__
Out[1]: <type 'type'>
# object มี type เป็น type

In [2]: type.__class__
Out[2]: <type 'type'>
# recursive structure นิ

#__bases__ attribute points to a tuple containing supertypes of an object
In [3]: object.__bases__
Out[3]: ()

In [4]: type.__bases__
Out[4]: (<type 'object'>,)
# เฮ้ยทำไม base ของ type เป็น object หล่ะ
# เจอปัญหาไก่กับไข่แล้ว

In [5]: isinstance(object, object)
Out[5]: True

In [6]: isinstance(type, object)
Out[6]: True


สรุปได้ว่า
  • <type 'object'> เป็น instance ของ <type 'type'>
  • <type 'object'> เป็น subtype ของ no object.
  • <type 'type'> เป็น instance ของตัวเอง.
  • <type 'type'> เป็น subtype ของ <type 'object'>.
<type 'type'> ก็คือ Metaclass ที่ดันเป็น subtype ของ instance ของตัวเอง

Related link from Roti