I came to Python from PHP, so I confused with some things I used to do in PHP. For example I got class Database_object which has some common database methods like this:
class DatabaseObject {
protected static $table_name;
protected static $db_fields;
public static function find_all() {
return self::find_by_query("SELECT * FROM ".static::$table_name);
}
...
private static function instantiate($record) {
$object = new self;
foreach($record as $attribute=>$value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
}
And some child classes like this:
class User extends DatabaseObject {
protected static $table_name = "users";
protected static $db_fields = array('id', 'gid', 'username', 'hashed_password', 'first_name', 'last_name', 'e_mail', 'phone_number', 'position', 'last_login', 'comment', 'supplier_id');
I got some question on static realisation, but now the topic is how to make this instantiate method in Python? I have method like this:
def FindAll(self):
query = 'SELECT * FROM ' + self._TableName
try:
self.cur.execute(query)
except(ValueError):
print("Error " + ValueError)
else:
return self.cur.fetchall()
But this one returns arrays and I want to make them objects like in instantiate method in PHP. For example if I call FindAll for user class. I want to get an array of users and then use them like:
for user in users:
print("Username: {}, Name: {} {}".format(user.username, user.first_name, user.second_name)
and not:
print("Username: {}, Name: {} {}".format(user[1], user[3], user[4]))
like it is now.