Python :使用 class 方法作为静态方法,当它作为实例方法实现时
Python : use a class methods as static , when its implemented as instance methods
我有一个很大的class,里面有很多功能和属性。
这些实例是根据远程数据库中的数据创建的。
创建每个实例的过程非常漫长和繁重。
为了性能起见,我从这个沉重的 class 中创建了一堆 class。
因此访问属性很容易并且效果很好。
问题是如何使用 class.
中的方法
例如:
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 工作,有没有办法我可以静态访问实例函数并覆盖 "self" var?
找到了解决问题的好方法:
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,如果您有权限,请重新设计代码。
我有一个很大的class,里面有很多功能和属性。 这些实例是根据远程数据库中的数据创建的。
创建每个实例的过程非常漫长和繁重。
为了性能起见,我从这个沉重的 class 中创建了一堆 class。 因此访问属性很容易并且效果很好。 问题是如何使用 class.
中的方法例如:
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 工作,有没有办法我可以静态访问实例函数并覆盖 "self" var?
找到了解决问题的好方法:
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,如果您有权限,请重新设计代码。