2016-04-28 7 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作品、私は静的にインスタンス機能にアクセスし、「自己」VARをオーバーライドすることができます方法はありますか?

+0

'class'または' def'ですか? –

+0

tnx、class。編集されました。 – dbkoren

+1

何をしていても、これは正しい/良い解決策から遠い巨大なHACKです。しかし、あなたがまだ他のクラスのメソッド/関数を 'bunchClsA'インスタンスに束縛しようとしているなら、' buncChlsA .__ getattr__'のようにすることができます: 'return types.MethodType(vars(clsA)[attr]、self)'これは誇りに思うかもしれないコードの一部ではありません。あなたのソースでこれを使用する場合は、この「ソリューション」の所有権を放棄することをお勧めします。私はなぜこのメソッドを '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 

をそして、これは私の問題、そのハックを解決し、あなたが権限を持っている場合は、コードを再設計します。

関連する問題