I'm working on a Proxy pattern in Python. I got the regular methods proxied properly using the __getattr__
method. However, the classmethod fails.
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'
I understand this fails since the 'User' class definition has no information about the DBClass while an instance of 'User' has information about the DBClass. How to solve what I'm trying to achieve here?
Additional Note: For the sake of simplicity, I've removed certain other aspects of the inheritance. In actual implementation:
I've multiple classes inheriting from DBClass
I've multiple classes inheriting from DBWrapper
An instance of DBClass-Child is what passed to the constructor of DBWrapper-Child - similar to the instantiation of User class.
I don't have control over DBClass. It is part of a library and I cannot change it.