[Tutor] Cannot understand object initiation
Alan Gauld
alan.gauld at btinternet.com
Sat Oct 12 18:42:54 CEST 2013
On 12/10/13 16:01, Kush Goyal wrote:
> Hi,
>
> I am learning web development by using flask framework. The below code
> is used to create a class LoginForm which inherits from the class
> Form.
>
> In the method 'validate' of class 'LoginForm' the variable 'user' is
> initialized by using:
>
> "user = User.query.filter_by ( username = self.username.data ).first()"
>
> now this I do not understand.
>
> Can a object be create by using a method of a class instead of the
> class consturctor? I mean shouldn't it be:
>
> user = User()
>
An object can be returned by any function or method.
Consider:
>>> class C:
... pass
...
>>> def f():
... return C()
...
>>> c1 = C()
>>> c2 = f()
>>> isinstance(c1,C)
True
>>> isinstance(c2,C)
True
>>>
> Later in the code "user.check_password(self.password.data)" is used.
> So here also how can check_password be used when the object 'user' has
> not been initiated using a constructor?
It has, but it was done inside the User.query.filter_by() method.
I don't know Flask but I assume this method initializes a
new empty User instance then populates it with data retrieved
from a database before returning the instance to its caller.
> Also, 'User' is a class which inherits from 'db.Model'. And db is
> initialized as: db = SQLAlchemy(app)
>
> So, here is db is an object and Model is a variable of class
> SQLAlchemy. Can someone please explain what is db.Model and can
> SQLAlchemy.Model be used in place of db.Model?
That requires a wee bit more detailed knowledge of SQLAlchemy.
My guess is that db.Model is a class. Classes are objects too
and can be stored as variables. Again, continuing the session
above:
>>> myclass = C
>>> c3 = myclass()
>>> isinstance(c3,C)
True
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list