टाइप हिंट्स

Intermediate Object-Oriented Programming in Python

Jake Roach

Data Engineer

टाइप हिंट्स के बिना कोड

class Student:
    def __init__(self, name, student_id, tuition_balance):
        self.name = name
        self.student_id = student_id
        self.tuition_balance = tuition_balance

# Trying to create a class can be tricky
walker = Student("Sarah Walker", 319921, 15000)
  • क्या student_id एक integer होना चाहिए?
  • tuition_balance float हो या integer? शायद string?
  • walker बनने के बाद, आगे कोड में उसका type कैसे याद रखें?
Intermediate Object-Oriented Programming in Python

टाइप हिंट्स

एक वैकल्पिक टूल जो ऑब्जेक्ट की जानकारी को कोड में जोड़ने देता है

  • पढ़ना, ट्रबलशूट करना आसान
  • एंटरप्राइज़-ग्रेड Python स्किल्स दिखाने के बेहतरीन तरीकों में से एक
  • इंटरप्रेटर इसे लागू नहीं करता
  • बिल्ट-इन type कीवर्ड, typing लाइब्रेरी, कस्टम क्लासेस
# वैरिएबल बनाते समय type hint जोड़ें
gpa: float = 3.92

# फंक्शन/मेथड डिफिनिशन में type hint जोड़ें def check_grades(year: str) -> List[int]: ...
# कस्टम क्लासेस भी उपयोग कर सकते हैं students: Dict[str, Student] = {...}
Intermediate Object-Oriented Programming in Python

बिल्ट-इन type कीवर्ड्स के साथ type hinting

# डिक्लेरेटिव लॉजिक के लिए type hinting
name: str = "Frost"  # पहले: name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# फंक्शन/मेथड डिफिनिशन के लिए type hinting
def get_schedule(semester: str) -> dict:
    ...
  • सिंटैक्स उपयोग करें variable: type
  • डिक्लेरेटिव, फंक्शन/मेथड का सिग्नेचर
  • रिटर्न type बताने के लिए def .... () -> type:
Intermediate Object-Oriented Programming in Python

typing लाइब्रेरी

typing एक लाइब्रेरी है जो type hint के और टूल देती है

  • List, Dict, Tuple
  • टॉप-लेवल ऑब्जेक्ट और उनके एलिमेंट्स को hint करें
from typing import List, Dict

student_names: List[str] = ["Morgan", "Chuck", "Anna"]
student_gpas: Dict[str, float] = {
    "Casey": 3.71,
    "Sarah": 4.0
}
  • Any, Set, Iterator, Callable
Intermediate Object-Oriented Programming in Python

कस्टम क्लासेस के साथ type hinting

class Student:
    def __init__(self, name: str, student_id: int, tuition_balance: float) -> None:
        self.name: str = name
        self.student_id: int = student_id
        self.tuition_balance: float = tuition_balance

    def get_course(self, course_id: str) -> Course:
        ...
        return course
# Student और Course को type hint में उपयोग करें
walker: Student = Student("Sarah Walker", 319921, 15000)
data_science: Course = walker.get_course("TDM-20100")
Intermediate Object-Oriented Programming in Python

ऑब्जेक्ट types जाँचना

# walker: Student = Student("Sarah Walker", 319921, 15000)
print(type(walker))
<class '__main__.Student'>
# data_science: Course = walker.get_course("TDM-20100")
print(type(data_science))
<class '__main__.Course'>
Intermediate Object-Oriented Programming in Python

अभ्यास करते हैं!

Intermediate Object-Oriented Programming in Python

Preparing Video For Download...