Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #41856 > unrolled thread
| Started by | Shiyao Ma <i@introo.me> |
|---|---|
| First post | 2013-03-26 14:19 +0800 |
| Last post | 2013-03-26 12:43 +0000 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: At a loss on python scoping. Shiyao Ma <i@introo.me> - 2013-03-26 14:19 +0800
Re: At a loss on python scoping. Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-03-26 12:43 +0000
| From | Shiyao Ma <i@introo.me> |
|---|---|
| Date | 2013-03-26 14:19 +0800 |
| Subject | Re: At a loss on python scoping. |
| Message-ID | <mailman.3718.1364278769.2939.python-list@python.org> |
[Multipart message — attachments visible in raw view] — view raw
PS, I now python's scoping rule is lexical rule (aka static rule). How does LEGB apply to class? On Tue, Mar 26, 2013 at 2:17 PM, Shiyao Ma <i@introo.me> wrote: > Hi, > suppose I have a file like this: > class A: > r = 5 > def func(self, s): > self.s = s > a = A() > print(a.r) # this should print 5, but where does py store the name of r > > a.func(3) > print(a.s) # this should print 3, also where does py store this name. > what's the underlying difference between the above example? > > > -- > My gpg pubring is available via: gpg --keyserver subkeys.pgp.net--recv-keys 307CF736 > > More on: http://about.me/introom > > -- My gpg pubring is available via: gpg --keyserver subkeys.pgp.net--recv-keys 307CF736 More on: http://about.me/introom
[toc] | [next] | [standalone]
| From | Steven D'Aprano <steve+comp.lang.python@pearwood.info> |
|---|---|
| Date | 2013-03-26 12:43 +0000 |
| Message-ID | <515197f1$0$29998$c3e8da3$5496439d@news.astraweb.com> |
| In reply to | #41856 |
On Tue, 26 Mar 2013 14:19:21 +0800, Shiyao Ma wrote:
> PS, I now python's scoping rule is lexical rule (aka static rule). How
> does LEGB apply to class?
It doesn't. Python does not use the same lookup rules for attributes and
unqualified names.
Attribute lookups follow inheritance rules. `instance.name` searches in
this order, from first to last:
if it exists, call instance.__class__.__getattribute__(name);
look in the instance __dict__;
look in the class __dict__;
for each superclass in the inheritance chain:
look in the superclass __dict__;
if it exists, call instance.__class__.__getattr__(name)
(the above is a little simplified, but is close enough for ordinary work).
Unqualified `name` follow this lookup rule:
if name is recognised by the compiler as a local name:
look in the local function namespace;
otherwise:
look in any enclosing function scopes;
look in the global scope;
look in the builtins.
--
Steven
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web