Python:将类方法用作静态,当它实现为实例方法时

时间:2016-04-28 08:35:01

标签: python oop static instance instance-variables

我有一个有很多功能和属性的大班。 实例是从远程数据库中的数据创建的。

创建每个实例的过程非常漫长而且很重。

在性能方面,我已经从这个沉重的类中创建了一个束类。 所以访问属性很容易,效果很好。 问题是如何使用该类中的方法。

前:

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

显然这个剂量工作,有没有办法可以静态访问实例函数并覆盖“self”var?

1 个答案:

答案 0 :(得分: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

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