我正在用Python开发一个代理模式。我使用__getattr__
方法正确地代理了常规方法。但是,classmethod失败。你知道吗
class DBClass(object):
def aMethod(self):
print 'aMethod'
@classmethod
def aClassMethod(cls):
print 'aClassMethod'
class DBWrapper(object):
def __init__(self, db = None):
super(DBWrapper, self).__init__()
self._db = db
def __getattr__(self, name):
if not self._db:
raise Exception("DBWrapper: DB is not initialized yet!")
if hasattr(self._db, name):
return getattr(self._db, name)
else:
raise AttributeError(name)
class User(DBWrapper):
def uMethod(self):
print 'uMethod'
@classmethod
def userClassMethod(cls):
cls.aClassMethod()
db = DBClass()
user = User(db)
user.uMethod() #prints uMethod
user.aMethod() #prints aMethod
user.aClassMethod() #prints aClassMethod
user.userClassMethod() #Fails with AttributeError: type object 'User' has no attribute 'aClassMethod'
我理解这是失败的,因为“User”类定义没有关于DBClass的信息,而“User”的实例有关于DBClass的信息。如何解决我要达到的目标?你知道吗
附加说明:为了简单起见,我删除了继承的某些其他方面。在实际实施中:
我有多个从DBClass继承的类
我有多个类从DBWrapper继承
DBClass Child的实例传递给DBWrapper Child的构造函数-类似于用户类的实例化。
我无法控制DBClass。它是图书馆的一部分,我不能改变它。
目前没有回答
相关问题 更多 >
编程相关推荐