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 कैसे याद रखें?एक वैकल्पिक टूल जो ऑब्जेक्ट की जानकारी को कोड में जोड़ने देता है
typing लाइब्रेरी, कस्टम क्लासेस# वैरिएबल बनाते समय type hint जोड़ें gpa: float = 3.92# फंक्शन/मेथड डिफिनिशन में type hint जोड़ें def check_grades(year: str) -> List[int]: ...# कस्टम क्लासेस भी उपयोग कर सकते हैं students: Dict[str, Student] = {...}
# डिक्लेरेटिव लॉजिक के लिए 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: typedef .... () -> type:typing एक लाइब्रेरी है जो type hint के और टूल देती है
List, Dict, Tuplefrom 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, Callableclass 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")
# 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