【问题标题】:Python: How to call ClassMethod from StaticMethodPython:如何从 StaticMethod 调用 ClassMethod
【发布时间】:2021-08-14 10:16:02
【问题描述】:

我正在开发一个已经建立的 Python 2.7 项目,需要进行一些修改,而且我对 Python 还是比较陌生,这就是我所做的:

我在同一个类中有两个函数,一个是@staticmethod,另一个是@classmethod。我需要从@staticmethod 内部调用@classmethod -

class ABC(object):

    @classmethod
    def classm(self, name):
        ...
    
    
    @staticmethod
    def staticm(freq):
        ...
        ...
        classm("sample")

上面这段代码不起作用,所以我将 staticmethod 转换为 classmethod 然后它工作正常(在正确的地方使用'self')

有人可以解释一下我们是否可以从 staticmethod 调用 classmethod(很可能似乎我不知道语法),如果不能,是否有更好的解决方法而无需转换?

【问题讨论】:

标签: python python-2.7 static-methods class-method


【解决方案1】:

首先,我想说的是,请尽量不要在类方法中使用 self ,因为社区使用 self 来传递实例,因此可能会混淆读者使用 cls 代替:

class ABC:
    @classmethod
    def classm(cls, name):
     ...

您可以使用ABC.classm("Sample")。 示例:

class ABC():
    @classmethod
    def classm(cls, name):
        print(name)

    @staticmethod
    def staticm(freq):
        ABC.classm(freq)


test = ABC()
test.staticm("Vedant")

如果您运行此代码,您将看到 Vedant 正在打印,并且静态方法正在调用类方法来执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-15
    • 2019-08-14
    • 1970-01-01
    • 2011-10-04
    • 2013-02-23
    • 1970-01-01
    • 2020-04-11
    相关资源
    最近更新 更多