如何有效和系统地过载Python类方法 [英] How to overload effectively and systematically Python class methods

查看:137
本文介绍了如何有效和系统地过载Python类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个Python(> = 2.6)类,有很多(数百!)个方法。现在有人想要继承它,但意识到大多数基类方法只需要一些简单的调整。此外,只有少数不同的方法可以调整这些方法。一些涉及输入转换,一些输出转换,一些涉及。

Assume that you have a Python (>=2.6) class with plenty (hundreds!) of methods. Now someone wants to subclass that but realized that most of the base class methods needs only some simple 'tuning'. Also there are only handful of different ways to tune those methods. Some involving input transformations, some output transformations, some both.

更具体一点我正在寻找一个(简单)继承的解决方案,我可以提供基类和应用特定转换的方法列表(列表),而不将此样板代码添加到每个重载方法。

To be more specific I'm looking for a (simple) solution for the inheritance where I just could provide the base class and a list (of lists) of methods to apply the specific transformations, without adding this boilerplate code to each overloaded method.

谢谢,

跟进。

根据gabo10yf的答案,我提出了一个解决方案:

Follow up.
Based on gabo10yf answer, I came up a solution as:

class B(object):
    def f1(self, val):
        print '1: ', val
    def f2(self, val):
        print '2: ', val
def decorator(f):
    def g(self, *args, **kwargs):
        print 'entering'
        result= f(self, *args, **kwargs)
    return g

class A(B):
    pass

_overridden= ['f1', 'f2']
def override(cls):
    for name in _overridden:
        setattr(cls, name, decorator(getattr(cls, name).im_func))
override(A)

if __name__== '__main__':
    b= B()
    b.f1(1)
    b.f2(2)
    a= A()
    a.f1(1)
    a.f2(2)

它似乎真的有效。然而感觉几乎太简单了,它肯定还必须包含一些模糊的问题?无论如何,多亏你们都让我弄清楚这一点!

It really seems to work. However it feels almost too simple, it surely must still contain some murky issues? Anyway thanks to you all letting me figure out this!

推荐答案

我希望这会有所帮助:


 # the base class
class B(object):
    def f1(self, val):
        pass
    def f2(self, val):
        pass

def decorator(cls,f):
def g( self,* args,** kwargs):
#do stuff
result = f(self,* args,** kwargs)
#do more stuff
return g

def decorator(cls, f): def g(self, *args, **kwargs): # do stuff result = f(self, *args, **kwargs) # do more stuff return g

A类(B):
_overridden = ['f1','f2']
@classmethod
def load(cls): cls._overridden中名称

setattr(name,decorator(getattr(name).im_func))

class A(B): _overridden = ['f1', 'f2'] @classmethod def load(cls): for name in cls._overridden: setattr(name, decorator(getattr(name).im_func))

A.load()

A.load()

为了处理类和静态方法,可能需要做一些更改。

One may have to do some changes in order to handle class and static methods.

这篇关于如何有效和系统地过载Python类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆