ovod
ovod

Reputation: 1178

python __setattr__ attribute issue

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.

Upvotes: 0

Views: 340

Answers (1)

acrosman
acrosman

Reputation: 12900

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()

Upvotes: 1

Related Questions