我想将method1从我的课堂之外添加到我的班级中。此外,我还想从我的课堂内部调用method1,以便将“家庭作业”更改为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())
但我收到了一个错误代码:
TypeError: method1() missing 1 required positional argument: 'self'
你能帮我一下吗?
发布于 2021-03-19 21:19:34
这个例子看起来很做作,我看不出它在其当前形式中的用法(在类的实例上执行的方法中在类上添加一个新方法)。
不过,要使它发挥作用,只需替换:
Sss.method1()
使用
self.method1()
因为添加的方法是作为实例方法,而不是类方法。
在旁白中,而不是
Sss.method1 = method1
最好使用:
self.__class__.method1 = method1
(减少对类名的依赖,并在类继承方案中工作得更好)
https://stackoverflow.com/questions/66715546
复制相似问题