2016-04-28 84 views
0

我有一个很大的类,它有很多函数和属性。 实例是从远程数据库中的数据创建的。Python:使用类方法作为静态,当它实现为实例方法

创建每个实例的过程非常漫长和沉重。

在表现中,我从这个沉重的班级中创造了一班。 因此,访问该属性很容易,而且效果很好。 问题是如何使用该类的方法。

例如:

class clsA(): 
    def __init__(self,obj): 
     self.attrA=obj.attrA 
    def someFunc(self): 
     print self 
class bunchClsA(bunch): 
    def __getattr__(self, attr): 
     # this is the problem: 
     try: 
      #try and return a func 
      func = clsA.attr 
      return func 
     except: 
      # return simple attribute 
      return self.attr 

很显然,这dosent工作,有没有一种方法,我可以staticly访问实例功能,并覆盖了“自我”变种?

+0

'class'或'def'? –

+0

tnx,类。编辑。 – dbkoren

+1

无论你在做什么,这是一个巨大的HACK,远非正确/好的解决方案。但是如果你仍然坚持将另一个类的方法/函数绑定到'bunchClsA'实例,那么你可以在'buncChlsA .__ getattr__'中这样做:'return types.MethodType(vars(clsA)[attr],self)'This不是人们可以引以为傲的代码。如果您在信息来源中使用这些信息,那么我建议放弃对此“解决方案”的所有权。我不明白为什么这比直接将方法写入'bunchClsA'更好。 – pasztorpisti

回答

0

找到了一个很好的解决问题的办法:

from bunch import Bunch 
import types 
#Original class: 
class A(): 
    y=6 
    def __init__(self,num): 
    self.x=num 
    def funcA(self): 
    print self.x 

#class that wraps A using Bunch(thats what i needed .. u can use another): 
class B(Bunch): 
    def __init__(self, data, cls): 
    self._cls = cls # notice, not an instance just the class it self 
    super(B, self).__init__(data) 

    def __getattr__(self, attr): 
    # Handles normal Bunch, dict attributes 
    if attr in self.keys(): 
     return self[attr] 
    else: 
     res = getattr(self._cls, attr) 
     if isinstance(res, types.MethodType): 
     # returns the class func with self overriden 
     return types.MethodType(res.im_func, self, type(self)) 
     else: 
     # returns class attributes like y 
     return res 

data = {'x': 3} 
ins_b = B(data, A) 
print ins_b.funcA() # returns 3 
print ins_b.y # returns 6 

这解决了我的问题,它是一个黑客,如果你有特权,重新设计的代码。