[英]call a method inside classmethod in python
我正在學習 python 並遇到了問題
假設我有一個類:
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()
我收到一個錯誤:
TypeError: square() missing 1 required positional argument: 'self'
我的嘗試:
我試圖將 square() 函數設為classmethod
然后調用 getsquare() 方法,但仍然出現錯誤(我猜這是因為我們沒有創建類的對象,因此由於這個數字沒有初始化)
但如果我喜歡這個它的工作原理:
class Xyz:
def square():
number=25
return number*number
@classmethod
def getsquare(cls):
return cls.square()
那么如何在類方法中調用類函數呢?
任何幫助或線索將被appriciated
我在這里看到了一些錯誤,但我將回答語法問題
@classmethod
/ @staticmethod
將方法裝飾為類的靜態成員。 根據定義,它們不引用任何對象並且有幾個限制:
在您的代碼中, getsquare
是一個靜態方法,而square
是一個實例方法。 所以, getsquare
違反了第一條規則,因為它調用了square
cls
只是一個未實例化的類對象,調用return cls.square()
類似於調用Xyz.square()
,這顯然不起作用,因為它不是@classmethod
。 在調用任何方法之前,先嘗試在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()
為什么第二個例子有效,簡單的答案是因為它沒有定義__init__
所以它不知道如何初始化所以不需要它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.