Reputation: 4859
I have some classes to access my collections in mongoDB. I've created a lot of methods for each class. Now I want to know if there is any way to implement these methods once and then my mongoDB classes only contains fields? look at this example:
#mongoBase.py
class MongoBase():
def insert()
pass
def update()
pass
#user.py
class User(MongoBase):
# Here should be only fields declaration and when I call .insert(), the fields should be inserted.
I did it in Java using java reflection. but I can't find something like that in python.
Upvotes: 0
Views: 58
Reputation: 1679
I'm pretty sure you can achieve what you're trying to do by simply referring to self
in the parent class.
Here's the code I used:
class MongoBase(object):
def insert(self, field, value):
setattr(self, field, value)
def update(self, field, value):
setattr(self, field, value)
class User(MongoBase):
def __init__(self, name):
self.name = name
And here's how it works:
>>> user = User('Bob')
>>> user.name
'Bob'
>>> user.update('name', 'Rob')
>>> user.name
'Rob'
>>> user.insert('age', 12)
>>> user.age
12
Upvotes: 1