Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>first, you should understand that</p> <pre><code>class Foo(object): bar = ['baz'] </code></pre> <p>and</p> <pre><code>class Foo(object): def __init__(self): self.bar = ['baz'] </code></pre> <p>Mean very different things, in the first case, <code>bar</code> is a class attribute, it is the same for all instances of <code>Foo</code>, and the class <code>Foo</code> itself (which is an instance of <code>type</code>, not <code>Foo</code>), with but in the second, <code>bar</code> is an attribute of each instance of <code>Foo</code>, and is not associated with the class at all!. If you try both, and append to the <code>bar</code>, for the first, the change will propagate to every instance of <code>Foo</code>, but for the second, only the instance you appended to will have that change.</p> <p>You can even set both!, you could do:</p> <pre><code>class Foo(object): bar = 'baz' def __init__(self): self.bar = 'quux' </code></pre> <p>And that's totally unanbigious. <code>Foo.bar == 'baz'</code>, <code>Foo().bar == 'quux'</code>, and you can get back to the class attribute from instances with <code>type(Foo()).bar == 'baz'</code></p> <p>so that means that the arguments in <code>__init__</code> in the tutorial, apply to instances of <code>User</code>, but the <code>Column</code> definitions apply to the class</p> <p>Sqlalchemy uses the <em>class</em> information, primarily. It uses it so that it can generate SQL which reads from and writes to the database in the proper way. Those definitions only really apply in the cases when sqlalchemy is converting instances of <code>User</code> to database calls, or trying to create instances of <code>User</code> when it receives rows from the database.</p> <p>You should regard the class attributes as <em>declaring the types</em>, and the instances attributes as <em>setting the values</em>.</p> <p>As for the matter of <em>when</em> sqlalchemy actually <em>uses</em> that information, there is a special bit of magic in <code>Base</code>, which is almost certainly from <code>sqlalchemy.ext.declarative.declarative_base()</code>. That function returns a <em>class</em>, and the class uses a <em>metaclass</em> which can track when new classes which derive from <code>Base</code> are defined. At the end of the class definition, even before you create instances of <code>User</code>, sqlalchemy looks at the <code>User</code> class to find the column properties it needs to know about.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload