0

I have a class designed to work with postgresql db:

dbclass = DBclass(1)
class DBclass(object):
    select_query    = 'SELECT * FROM "{table}" WHERE {table}_id=%s'

    def __init__(self, id=None):
            self.__id       = id
            self.__table    = self.__class__.__name__.lower()

And I have __setattr__ overloaded:

def __setattr__(self, name, value):
    super(DBclass, self).__setattr__(name, value)
    self.load()

And method used to connect to load content from db:

def load(self):
    # Here I send select query and get two remaining values

With this __setattr__ I only can initialize __id and __table values. There are still two fields which are in my database which are not loading. I can not initialize them using __setattr__ because __table variable is not initialised yet as well as __id and python can not call load method and send query.

Perhaps I put wrong logic in my decision and values from db shouldn't be initiated like that.

acrosman
  • 12,814
  • 10
  • 39
  • 55
ovod
  • 1,118
  • 4
  • 18
  • 33
  • Next time, include the error you're getting when you try to assign values. I suspect load() triggers a couple different errors depending on the conditions and it would be easier to be confident about responses when the errors are included. It also helps show that you've tried a couple things before asking for help. – acrosman Mar 10 '15 at 13:47

1 Answers1

1

It seems likely that your load() method will assign your other two values which means it will be calling __setattr__() at least twice. Unless you have logic in load() to avoid it you almost certainly creating an infinite loop. A basic load method is not likely something you want to call from within __setattr__() as it would likely have unexpected side effects (for example any time you update any value on the object, all the values in the database would get reset).

Just move the load() into __init__() and get rid of __setattr__() entirely.

 def __init__(self, id=None):
    self.__id       = id
    self.__table    = self.__class__.__name__.lower()
    self.load()
acrosman
  • 12,814
  • 10
  • 39
  • 55
  • Yeap, good advice. But is there any way in python to put load into setattr so first __table would be initiated and then load method called? – ovod Mar 10 '15 at 13:59
  • Sure: make the load call conditional on the existence of __table. That's still probably not a great idea; you'll need to do something to prevent load() from calling __setattr__(), which is also possible but ugly. You should make sure you have a really good reason to justify that design choice. – acrosman Mar 10 '15 at 14:19