Adding method to the class from outside of the class
Question:
I want to add method1 to my class from outside of my class. Also I want to call method1 from inside of my class in order to changing the ‘homework’ to 0
def method1(self):
print("Processing.....")
print("Done :D")
self.homework = 0
class S:
homework = 10
def homeworkremover(self):
S.method1 = method1
S.method1()
a = S()
print(a.homeworkremover())
But I’ve received an error code:
TypeError: method1() missing 1 required positional argument: 'self'
Can you help me out pls?
Answers:
The example seems quite contrived, I can’t quite see the use of it in its current form (adding a new method on a class from within a method that is being executed on an instance of the class).
But to make it work nevertheless, simply replace:
Sss.method1()
with
self.method1()
since the added method is intended as an instance method and not a class method.
On a side note, instead of
Sss.method1 = method1
it might be better to use:
self.__class__.method1 = method1
(less dependent on the class name, and works better as well in class inheritance scenarios)
I want to add method1 to my class from outside of my class. Also I want to call method1 from inside of my class in order to changing the ‘homework’ to 0
def method1(self):
print("Processing.....")
print("Done :D")
self.homework = 0
class S:
homework = 10
def homeworkremover(self):
S.method1 = method1
S.method1()
a = S()
print(a.homeworkremover())
But I’ve received an error code:
TypeError: method1() missing 1 required positional argument: 'self'
Can you help me out pls?
The example seems quite contrived, I can’t quite see the use of it in its current form (adding a new method on a class from within a method that is being executed on an instance of the class).
But to make it work nevertheless, simply replace:
Sss.method1()
with
self.method1()
since the added method is intended as an instance method and not a class method.
On a side note, instead of
Sss.method1 = method1
it might be better to use:
self.__class__.method1 = method1
(less dependent on the class name, and works better as well in class inheritance scenarios)