I'm trying to create a class
to adapt django
objects to the export. I want other programmers to always inherit from this class
and if needed, they can override any attribute by overriding:
get__<attr_name>
method.
So what I do is that I iterate over django
model fieldnames and for every fieldname, I set get__<attr_name>
method. The problem is that all these methods returns the same True
which is an output of the last fieldname.
class BaseProductExportAdapter():
def __init__(self, product: Product):
self.product = product
self.eshop = self.product.source.user_eshop
def _set_methods(self):
product_attr_names = Product.get_fieldnames(exclude=[])
# set all getters so we can use get__<any_field> anytime. It can be overriden anytime.
for attr_name in product_attr_names:
setattr(self, 'get__' + attr_name, lambda: getattr(self.product, attr_name))
When I create a BaseProductExportAdapter
instance and set product
as an argument and call b._set_methods()
, I see this:
>>> ...
>>> b._set_methods()
>>> b.get__quantity()
>>> True
>>> b.get__<any_valid_fieldname>()
>>> True
Do you know why it doesn't work correctly?