वैकल्पिक constructors
Python आपको @classmethod डेकोरेटर और एक विशेष पहला आर्ग्युमेंट cls का उपयोग करके class methods परिभाषित करने देता है। Class methods का मुख्य उपयोग ऐसे methods परिभाषित करना है जो class का एक instance लौटाएँ, लेकिन __init__() जैसा ही कोड न इस्तेमाल करें।
उदाहरण के लिए, आप एक time series पैकेज विकसित कर रहे हैं और तारीखों के साथ काम करने के लिए अपनी class BetterDate बनाना चाहते हैं। इस class के attributes year, month, और day होंगे। आप ऐसा constructor चाहते हैं जो year, month, और day की वैल्यू दिए जाने पर BetterDate ऑब्जेक्ट बनाए, और साथ ही ऐसी strings जैसे 2020-04-30 से भी BetterDate ऑब्जेक्ट बनाने की सुविधा हो।
निम्नलिखित फंक्शंस आपके काम आ सकते हैं:
.split("-")method किसी string को"-"पर बाँटकर एक array में बदल देगा, जैसे"2020-04-30".split("-")["2020", "04", "30"]लौटाता है,int()किसी string को नंबर में बदलेगा, जैसेint("2019")2019होता है।
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
class BetterDate:
# Constructor
def __init__(self, year, month, day):
# Recall that Python allows multiple variable assignments in one line
self.year, self.month, self.day = year, month, day
# Define a class method from_str
____
def from_str(____, datestr):
# Split the string at "-" and convert each part to integer
parts = datestr.split("-")
year, month, day = int(parts[0]), ____, ____
# Return the class instance
____ ____(____, ____, ____)
bd = BetterDate.from_str('2020-04-30')
print(bd.year)
print(bd.month)
print(bd.day)