[Tutor] methods and functions
Magnus Lyckå
magnus@thinkware.se
Fri Jun 13 14:37:09 2003
At 10:54 2003-06-13 -0700, Gerardo Arnaez wrote:
>How can an instance of a class NOT have an attribute
>that has been defined for that class.
The instance *never* has an attribute just because
its class has an attribute. They are two different
objects.
When python reaches the code:
class X:
...
it creates a *class* object, and calls it X.
When python reaches the code:
x1 = X()
it creates an *instance* object, which will have an
attribute x1.__class__ = X.
>>> class X:
... a = 'Attribute in class X'
...
>>> type(X)
<type 'class'>
>>> x1 = X()
>>> type(x1)
<type 'instance'>
>>> x1.a
'Attribute in class X'
>>> x1.a = 'Attribute in instance x1'
>>> x1.a
'Attribute in instance x1'
>>> x1.__dict__
{'a': 'Attribute in instance x1'}
>>> X.__dict__
{'a': 'Attribute in class X', '__module__': '__main__', '__doc__': None}
The same mechanism exists whether the attributes are
strings, functions, or anything else.
>>> class X:
... def hi(self):
... print "Hi"
...
>>> X.hi
<unbound method X.hi>
>>> type(X.hi)
<type 'instance method'>
>>> x = X()
>>> x.hi
<bound method X.hi of <__main__.X instance at 0x01185B00>>
>>> type(x.hi)
<type 'instance method'>
>>> X.__dict__
{'__module__': '__main__', 'hi': <function hi at 0x01188140>, '__doc__': None}
>>> x.__dict__
{}
You see? Here, the method "hi" is an attribute of the class X.
It's *not* an attribute of the instance object x. But it's been
bound to x...
To connect to another recent thread, we can add a method to
the actual instance object as well...
>>> x.hi()
Hi
This is what we expect. The x object uses the method defined in
its class. Let's give it its completely private instance method!
>>> import new
>>> def myHello(self):
... print "Hello there!!!"
...
>>> x.hi = new.instancemethod(myHello, x, X)
>>> x.__dict__
{'hi': <bound method X.myHello of <__main__.X instance at 0x01185B00>>}
As you see, it now has an attribute 'hi', which is a bound method.
>>> X.__dict__
{'__module__': '__main__', 'hi': <function hi at 0x01188140>, '__doc__': None}
But the class X still looks just the same... So, how does x
behave now?
>>> x.hi()
Hello there!!!
It uses the "hi" which is defined most closely of course...
But you can still do:
>>> X.hi(x)
Hi
Confused yet? :)
As you see, the plain and simple python interpreter and the
standard functions Python has for introspection lets you explore
a lot of things...
--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language