what is happening at __init__
Benjamin Tai
bt98 at doc.ic.ac.uk
Mon Mar 4 06:21:36 EST 2002
Hi,
I was simply curious, finding out what is happening at the class
constructor. The followings are the questions/answers that I come up
with, in related with my program attached:
Q 1) "self" is already assigned to the instance of the class at the
point entering the constructor.
Q 2) Although "self" is assigned to a new value within the function, it
is in a local scope.
Q 3) A constructor must return None, it cannot return "self".
Q 4) The address of instance matches with the instance within the
constructor.
Q 5) Even though the constructor returns None, the instance is properly
initialised (with inherited attributes).
The following is my program:
#############
class A:
x = 100
class B(A):
def __init__(self):
# Q1
print 'inside constructor self is ', self
self = 300
# Q2
print 'inside constructor self is ', self
# Q3
return None
b = 200
b = B()
print 'after constructor instance b is ', b
# Q4
print 'instance b contains attribute x, valued ', b.x
# Q5
############
The following is the trace:
prompt > inside constructor self is <__main__.B instance at 0x80e9c94>
prompt > inside constructor self is 300
prompt > after constructor instance b is <__main__.B instance at
0x80e9c94>
prompt > instance b contains attribute x, valued 100
Could anyone tell me whether the explanation is correct or not? Any
comments would be appreciated.
Thanks
Ben
More information about the Python-list
mailing list