简体   繁体   English

Python:避免同时定义classmethod和instancemethod

[英]Python: avoid defining both a classmethod and an instancemethod

NOTE on the question below. 关于以下问题的说明。 I think the 'proper' pythonic idiom is to a) create module functions, such as foo_math below, and then call their specific action against an instance within the class itself. 我认为“正确的”pythonic习语是a)创建模块函数,例如下面的foo_math ,然后针对class本身内的实例调用它们的特定操作。 The bottom piece of code reflects that approach. 最底层的代码反映了这种方法。


I want to define a classmethod which takes two arguments and returns a value. 我想定义一个classmethod ,它接受两个参数并返回一个值。 I want the same method to be able to be called on a class instance with the instance value pass as one of the arguments. 我希望能够在class实例上调用相同的方法,并将实例值pass作为参数之一。 Can I do this without defining two distinct methods as I have done here? 如果没有像我在这里所做的那样定义两种不同的方法,我能这样做吗

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)

What I would like is: 我想要的是:

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

Short of subtyping int , here is my conclusion to this question: 没有子类型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)

I don't think that you can call a method from a class without defining an object of that class (class methods don't belong inside the methods of any one class), so things like Foo.math(3, 4) will return a NameError as Foo has not been defined. 我不认为你可以调用从类中的方法不限定类的一个对象(类方法没有任何一个类的方法里面属于),所以像Foo.math(3, 4)将返回尚未定义名为FooNameError

With this in mind, you should modify your code to be like this (even though with the problem solved there are still some issues with the code): 考虑到这一点,您应该将代码修改为这样(即使解决了问题,代码仍然存在一些问题):

# 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)

Then you can do: 然后你可以这样做:

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

i don't recommend doing this, but if you really want, it's this (thank you other guy on stackoverflow for first part): 我不建议这样做,但如果你真的想要,就是这个(感谢stackoverflow上的其他人第一部分):

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

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

then, do something like 那么,做点什么

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

but maybe you just want to define the __add__ and __radd__ methods... 但也许你只想定义__add____radd__方法......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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