我正在使用 @classobj 实现多个构造函数。我不仅设置了变量,还调用了新类中的方法:
class Example:
def __init__(self):
pass
@classmethod
def constructor1(cls,x,y):
self=cls
self.__x = x
self.__somemethod(self,y)
...
我收到以下错误:
unbound method __somemethod() must be called with Example instance as
first argument (got classobj instance instead)
我该如何解决这个问题?
请您参考如下方法:
如果您希望您的类方法成为构造函数,您可能希望创建您作为 cls 传入的类的实例。我怀疑您正在尝试使用 self = cls 行来执行此操作,但您实际上并没有创建新实例,因为您忽略了括号。还有其他一些问题,但我认为这是关键。这是一个固定的构造函数:
@classmethod
def constructor1(cls,x,y):
self=cls() # parentheses added, to make it a call
self.__x = x
self.__somemethod(y) # self is not needed as a parameter here
return self # return the new instance
