繁体   English   中英

在python中调用classmethod内部的方法

[英]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将方法装饰为类的静态成员。 根据定义,它们不引用任何对象并且有几个限制:

  • 它们只能直接调用其他静态方法
  • 他们只能直接访问静态数据
  • 他们不能以任何方式提及 self 或 super

在您的代码中, 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM