हिंदी

If we want to make a method that is added dynamically to a class available to all the instances of the class, how can it be done? Explain with an example.

Advertisements
Advertisements

प्रश्न

If we want to make a method that is added dynamically to a class available to all the instances of the class, how can it be done? Explain with an example.

कोड लेखन
स्पष्ट कीजिए
Advertisements

उत्तर

Assign the function to the class, not to a particular object. Then every existing and future instance can use that method.

class HealthProfile:
    def __init__(self, name):
        self.name = name


# Function defined outside the class
def play(self):
    print(self.name, "is playing")


# Add the function dynamically to the class
HealthProfile.play = play

h1 = HealthProfile("Shalini")
h2 = HealthProfile("Ritu")
h1.play()
h2.play()
Shalini is playing
Ritu is playing

Note: Use HealthProfile.play = play, not HealthProfile.play = play(). Writing play() would call the function immediately instead of attaching it as a method.

shaalaa.com
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 3: Classes in Python - EXERCISE [पृष्ठ ६२]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
अध्याय 3 Classes in Python
EXERCISE | Q 13. | पृष्ठ ६२
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×