English

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

Question

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.

Code Writing
Explain
Advertisements

Solution

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
  Is there an error in this question or solution?
Chapter 3: Classes in Python - EXERCISE [Page 62]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 3 Classes in Python
EXERCISE | Q 13. | Page 62
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×