In the following code, is the attribute (variable/member) a class attribute
or an instance attribute? I thought that it was an instance attribute and
that the class attribute was created in __init__().
My biggest question is why self.v has a value of "Consequences" in the
_init__() of f2? Is self.v not an instance variable?
pwatson [ /home/pwatson/src/python/c ] 270
$ cat d.py
#! /usr/bin/env python
class whatisit:
v = "Ambiguous"
def __init__(self):
print '=== __init__', self.v, whatisit.v
self.v = "Truth"
whatisit.v = "Consequences"
def showem(self):
print '=== showem ', self.v, whatisit.v
if (__name__ == "__main__"):
f1 = whatisit()
f1.showem()
f2 = whatisit()
f2.showem()
pwatson [ /home/pwatson/src/python/c ] 271
$ ./d.py
=== __init__ Ambiguous Ambiguous
=== showem Truth Consequences
=== __init__ Consequences Consequences
=== showem Truth Consequences
I give you a subtle example:
class C(object):
x=1 # class attribute
def __init__(self):
self.x=self.x # the class attribute becomes an instance attribute
c=C()
C.x=2
print c.x,C.x
This code prints 1,2. You see that the line self.x=self.x is far
from being trivial: Python looks first for the self on the right,
looking for the instance attribute self.x: since it does not find anything,
it looks for the class attribute; then the class attribute
is assigned to the instance attribute on the left hand side.
If you forget the apparently useless self.x=self.x line, you get a
different result:
class C(object):
x=1 # class attribute
def __init__(self):
pass
c=C()
C.x=2
print c.x,C.x
This prints 2,2, since the class attribute has been changed to 2
and c has no instance attribute.
Hoping-having-not-increased-your-confusion-ly,
Michele
When an attribute lookup fails in an instance, Python searches the
namespace of the parent class and all of the parent's base classes (but
*not* the namespaces of the metaclasses).
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/
"In many ways, it's a dull language, borrowing solid old concepts from
many other languages & styles: boring syntax, unsurprising semantics,
few automatic coercions, etc etc. But that's one of the things I like
about it." --Tim Peters on Python, 16 Sep 93
Thanks for everyone's help, including Mike.
"Michele Simionato" <mi...@pitt.edu> wrote in message
news:2259b0e2.03042...@posting.google.com...
class Foo (object) :
foo = 'spam'
def __init__ (self) :
print Foo.foo, self.foo
self.foo = 'ham'
print Foo.foo, self.foo
>>> f = Foo()
spam spam
spam ham
>>> print f.foo, Foo.foo
ham spam