0

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?

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Well, no those are two different things semantically. Whether it works "better in inheritance situations" depends on what you intend
If I use Sss.method1(self) instead of Sss.method1(),what would happen?Would method1 belong to Sss class?
Ok guys I've solved my problem thanks for your answers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.