[英]call a method inside classmethod in python
I am learning python and stucked in a problem我正在学习 python 并遇到了问题
Suppose I have a class:假设我有一个类:
class Xyz:
def __init__(self):
self.number=25
def square(self):
return self.number*self.number
@classmethod
def getsquare(cls):
return cls.square()
#Now let's call getsquare() method
sq=Xyz.getsquare()
I am getting an error:我收到一个错误:
TypeError: square() missing 1 required positional argument: 'self'
My attempt:我的尝试:
I tried to make square() function as classmethod
and then calling the getsquare() method but still I am getting an error (I guess it was because since we aren't creating an object of class so due to this number is not initialising)我试图将 square() 函数设为
classmethod
然后调用 getsquare() 方法,但仍然出现错误(我猜这是因为我们没有创建类的对象,因此由于这个数字没有初始化)
but if I do like this it's working:但如果我喜欢这个它的工作原理:
class Xyz:
def square():
number=25
return number*number
@classmethod
def getsquare(cls):
return cls.square()
so How to call a class function inside classmethod?那么如何在类方法中调用类函数呢?
any help or clue will be appriciated任何帮助或线索将被appriciated
Some mistakes I see here, but I am going to answer the syntax question我在这里看到了一些错误,但我将回答语法问题
@classmethod
/ @staticmethod
decorate a method as a static member for the class. @classmethod
/ @staticmethod
将方法装饰为类的静态成员。 By definition, they do not reference to any object and have several restrictions:根据定义,它们不引用任何对象并且有几个限制:
In your code, getsquare
is a static method and square
is a instance method.在您的代码中,
getsquare
是一个静态方法,而square
是一个实例方法。 So, getsquare
violates the first rule because of it is calling to square
所以,
getsquare
违反了第一条规则,因为它调用了square
cls
is just an uninstantiated class object, calling return cls.square()
is analogous to calling Xyz.square()
, which obviously doesn't work because its not a @classmethod
. cls
只是一个未实例化的类对象,调用return cls.square()
类似于调用Xyz.square()
,这显然不起作用,因为它不是@classmethod
。 Try first initiating the class inside getsquare
before calling any methods:在调用任何方法之前,先尝试在
getsquare
初始化类:
class Xyz:
def __init__(self):
self.number=25
def square(self):
return self.number*self.number
@classmethod
def getsquare(cls):
return cls().square()
#Now let's call getsquare() method
sq=Xyz.getsquare()
Why the second example works, the simple answer is because it doesn't have an __init__
defined so it's doesn't know how to initialize so it's not needed.为什么第二个例子有效,简单的答案是因为它没有定义
__init__
所以它不知道如何初始化所以不需要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.