Python:避免同时定义classmethod和instancemethod

时间:2014-02-24 20:13:43

标签: python

关于以下问题的说明。我认为'正确'的pythonic习语是a)创建模块函数,例如下面的foo_math,然后针对class本身内的实例调用它们的特定操作。最底层的代码反映了这种方法。


我想定义一个classmethod,它接受​​两个参数并返回一个值。我希望能够在class实例上调用相同的方法,并将实例值pass作为参数之一。如果没有像我在这里所做的那样定义两种不同的方法,我可以这样做吗?

class Foo(object):
    __init__(x):
        self.x = x

    @classmethod
    def foo_math(cls, x, y):
         return x + y

    def math(self, y):
        return Foo.foo_math(self.x, y)

我想要的是:

>>> Foo.math(3, 4)
7
>>> f = Foo()
>>> f.x = 3
>>> f.math(4)
7

没有子类型int,这是我对这个问题的结论:

def foo_math(cls, x, y):
     return x + y

class Foo(object):
    __init__(x):
        self.x = x

    def foo_math(self, y):
        return foo_math(self, y)

2 个答案:

答案 0 :(得分:1)

我认为你不能在没有定义该类的对象的情况下调用类中的方法(类方法不属于里面任何一个类的方法),所以像<{1}}将返回Foo.math(3, 4),因为NameError尚未定义。

考虑到这一点,您应该将代码修改为这样(即使解决了问题,代码仍然存在一些问题):

Foo

然后你可以这样做:

# A class method would probably go here somewhere.

class Foo(object):
    def __init__(self, x):
        self.x = x

    def foo_math(self, x, y):
         return x + y

    def math(self, y):
        return self.foo_math(self.x, y)

答案 1 :(得分:1)

我不建议这样做,但如果你真的想要,就是这个(感谢stackoverflow上的其他人第一部分):

class staticorinstancemethod(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, owner):
        return functools.partial(self.func, instance)

然后,做一些像

这样的事情
class F(object):
    @staticorinstancemethod
    def math(instOrNone, v1, v2=None):
        return instOrNone.x + v1 if instOrNone else v1 + v2

但也许您只想定义__add____radd__方法......