פונקציית type של Python [עם דוגמאות קלות]

אנו משתמשים בפונקציית type() ב-Python כדי לזהות את סוג האובייקט של אובייקט Python מסוים. זו פונקציה ישירה ופשוטה להבנה. ללא כל המון מילים, בואו נתקדם ישירות לתחביב.

תחביב בפונקציית type() של Python

יש ל-Python הרבה פונקציות מובנות. פונקציית type() משמשת לקבלת הסוג של אובייקט.

התחביב של פונקציית type() ב-Python הוא:

type(object)

type(name, bases, dict)

כאשר מועבר ארגומנט יחיד לפונקציית type(), היא מחזירה את סוג האובייקט. ערכו זה זהה למשתנה המופע object.__class__.

כאשר מועברים שלושה ארגומנטים, היא מחזירה אובייקט סוג חדש. היא משמשת ליצירת קלאס דינמי בצורה דינמית.

  • מחרוזת "name" הופכת לשם הקלאס. זה זהה למאפיין המופע __name__ של קלאס.
  • טאפל "bases" מציינת את הקלאסים הבסיסיים. זה זהה למאפיין המופע __bases__ של הקלאס.
  • מילון "dict" מסייע ליצירת גוף הקלאס. זה זהה למאפיין המופע __dict__ של הקלאס.

דוגמאות לפונקציית type() בפייתון

בואו נסתכל על כמה דוגמאות לשימוש בפונקציית type().

1. מציאת סוג של אובייקט בפייתון

x = 10
print(type(x))

s = 'abc'
print(type(s))

from collections import OrderedDict

od = OrderedDict()
print(type(od))

class Data:
    pass

d = Data()
print(type(d))

פלט:

<class 'int'>
<class 'str'>
<class 'collections.OrderedDict'>
<class '__main__.Data'>

שימו לב שהפונקצייה type() מחזירה את סוג האובייקט עם שם המודול. מאחר שבסקריפט שלנו בפייתון אין מודול, המודול שלו הופך להיות __main__.

2. חילוץ פרטים ממחלקות בפייתון

נניח שיש לנו את המחלקות הבאות. נחלץ מידע על המחלקות באמצעות התכונות class, bases, dict, ו-doc.

class Data:
    """Data Class"""
    d_id = 10


class SubData(Data):
    """SubData Class"""
    sd_id = 20

בואו נדפיס חלק מהתכונות של מחלקות אלו.

print(Data.__class__)
print(Data.__bases__)
print(Data.__dict__)
print(Data.__doc__)

print(SubData.__class__)
print(SubData.__bases__)
print(SubData.__dict__)
print(SubData.__doc__)

פלט:

<class 'type'>
(<class 'object'>,)
{'__module__': '__main__', '__doc__': 'Data Class', 'd_id': 10, '__dict__': <attribute '__dict__' of 'Data' objects>, '__weakref__': <attribute '__weakref__' of 'Data' objects>}
Data Class

<class 'type'>
(<class '__main__.Data'>,)
{'__module__': '__main__', '__doc__': 'SubData Class', 'sd_id': 20}
SubData Class

ניתן ליצור מחלקות דומות באמצעות פונקציית type().

Data1 = type('Data1', (object,), {'__doc__': 'Data1 Class', 'd_id': 10})
SubData1 = type('SubData1', (Data1,), {'__doc__': 'SubData1 Class', 'sd_id': 20})

print(Data1.__class__)
print(Data1.__bases__)
print(Data1.__dict__)
print(Data1.__doc__)

print(SubData1.__class__)
print(SubData1.__bases__)
print(SubData1.__dict__)
print(SubData1.__doc__)

פלט:

<class 'type'>
(<class 'object'>,)
{'__doc__': 'Data1 Class', 'd_id': 10, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Data1' objects>, '__weakref__': <attribute '__weakref__' of 'Data1' objects>}
Data1 Class

<class 'type'>
(<class '__main__.Data1'>,)
{'__doc__': 'SubData1 Class', 'sd_id': 20, '__module__': '__main__'}
SubData1 Class

שימו לב שלא ניתן ליצור פונקציות במחלקה דינמית באמצעות פונקציית type().

שימוש בחיי-אמת של פונקציית ה-type()

פייתון היא שפת תכנות בעלת טיפוס דינמי. לכן, אם נרצה לדעת את הסוג של הארגומנטים, אנו יכולים להשתמש בפונקציית type(). אם ברצונך לוודא כי הפונקציה שלך עובדת רק על סוגי אובייקטים ספציפיים, השתמש בפונקציית isinstance().

נניח שנרצה ליצור פונקציה לחישוב משהו על שני מספרים שלמים. נוכל לממש את זה בדרך הבאה.

def calculate(x, y, op='sum'):
    if not(isinstance(x, int) and isinstance(y, int)):
        print(f'Invalid Types of Arguments - x:{type(x)}, y:{type(y)}')
        raise TypeError('Incompatible types of arguments, must be integers')
    
    if op == 'difference':
        return x - y
    if op == 'multiply':
        return x * y
    # הגדרת ברירת המחדל היא סכימה
    return x + y

פונקציית isinstance() משמשת לאימות סוג הארגומנט הקלט. פונקציית type() משמשת להדפסת הסוג של הפרמטרים כאשר אימות נכשל.

מקורות

  • מסמכי API של type()
  • פונקציית isinstance() בפייתון
  • בדיקת סוגי נתונים בפייתון

Source:
https://www.digitalocean.com/community/tutorials/python-type