Class attributes बदलना
आपने सीखा कि class attributes कैसे परिभाषित किए जाते हैं और उन्हें class instances से कैसे एक्सेस किया जाता है. तो क्या होगा अगर आप किसी instance से एक्सेस करते समय किसी class attribute को कोई और मान असाइन करने की कोशिश करें?
पिछले अभ्यास की Player class पहले से परिभाषित है, जैसा नीचे दिखाया गया है:
class Player:
MAX_POSITION = 10
def __init__(self, position):
if position <= Player.MAX_POSITION:
self.position = position
else:
self.position = Player.MAX_POSITION
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में Object-Oriented Programming परिचय
अभ्यास निर्देश
- दो
Playerऑब्जेक्ट बनाइए:p1औरp2, जिनकी positions क्रमशः9और5हों. p1.MAX_POSITIONऔरp2.MAX_POSITIONप्रिंट करें.p1.MAX_POSITIONको7असाइन करें.p1.MAX_POSITIONऔरp2.MAX_POSITIONदोबारा प्रिंट करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# Create Players p1 and p2
p1 = ____
p2 = ____
print("MAX_POSITION of p1 and p2 before assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____
# Assign 7 to p1.MAX_POSITION
____
print("MAX_POSITION of p1 and p2 after assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____