混合了@classmethod和方法的python类

时间:2015-12-02 21:28:33

标签: python

您好我在与不同合作者合作的项目中开发课程。我已经能够用不同的方法实现该类,并且所有方法都正常工作。基本上我现在的情况如下

class MyClass(object):
    def __init__(self,a,b,c):
        self.a = a
        self.b = b
        self.c = c  

    def one(self,**kwargs):
        d = self.two()
        e = self.three()
        # make something using a an b like 
        return 2*d + 3*e

    def two(self,**kwargs):
        # this uses a for example 
        return self.a*2 + self.b**self.c
    def three(self, **kwargs):
        # this uses b and c
        return self.b/self.c - self.a/3

这些都是明显的例子,还有更复杂的东西在继续。问题是这个类只能通过实例

调用
[1]: x=MyClass(a,b,c)
[2]: y=x.one()

该类被插入一个较大的项目中,其他协作者想直接调用一个

[1]: y = MyClass.one(a,b,c)
[2]: z = MyClass.two(a,b,c)
[3]: x = MyClass.three(a,b,c)

我知道我可以通过使用装饰器来获得它,比如@classmethod。例如我可以做的一个

@classmethod
def one(cls, a, b, c):
    d = self.two()
    e = self.three()
    cos(2*d+3*e)

但这实际上不起作用,因为它会因为未定义self而引发错误。我的问题是,如果我没有创建实例,我不明白@classmethod如何调用同一个类中的另一个方法。顺便说一下,我正在使用python 2.7 谢谢你的任何线索。我试图搜索各种@classmethod问题,但没有找到答案(或者我可能不理解)

1 个答案:

答案 0 :(得分:0)

您已将参数重命名为cls,因此您必须将功能正文中的self更改为cls。名称selfcls只是普通标识符,是一种惯例,与例如C ++的this

@classmethod
def one(cls, a, b, c):
    d = cls.two()
    e = cls.three()
    cos(2*d+3*e)

的作用相同
@classmethod
def one(we_need_more_unicorns, a, b, c):
    d = we_need_more_unicorns.two()
    e = we_need_more_unicorns.three()
    cos(2*d+3*e)

或者更合理的标识符,例如Cls(用大写的C表示它是一个类),有时也可以看到。