【问题标题】:Python : use a class methods as static , when its implemented as instance methodsPython:使用类方法作为静态方法,当它作为实例方法实现时
【发布时间】:2016-04-28 08:35:01
【问题描述】:

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

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

出于性能考虑,我从这个重类中创建了一堆类。 所以访问属性很容易并且效果很好。 问题是如何使用该类中的方法。

前:

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?

【问题讨论】:

  • tnx,类。已编辑。
  • 无论您在做什么,这都是一个巨大的 HACK,远非正确/好的解决方案。但是,如果您仍然坚持将另一个类的方法/函数绑定到bunchClsA 实例,那么您可以在buncChlsA.__getattr__ 中这样做:return types.MethodType(vars(clsA)[attr], self) 这不是一段可以引以为豪的代码。如果您在您的资源中使用它,那么我建议您放弃对这个“解决方案”的所有权。我不明白为什么这比直接将方法写到bunchClsA 更好。
  • 您到底想做什么,有什么问题?怎么不行?
  • 我知道这是一个 hack,我尽量不复制所有方法(有很多。),谢谢你的想法。
  • 你为什么不使用多重继承?

标签: python oop static instance instance-variables


【解决方案1】:

找到了解决问题的好方法:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-07
    • 2010-10-26
    • 1970-01-01
    • 2011-07-25
    • 2011-01-04
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    相关资源
    最近更新 更多