[Tutor] Class vs. instance

Alan Gauld alan.gauld at btinternet.com
Wed Jan 18 09:52:28 CET 2012


On 18/01/12 02:13, Stayvoid wrote:

> class A:
> 	def __init__(self, data):
> 		self.data = data
> 		print self.data
>
> I'm trying to understand this function-like syntax:
> A('foo').__init__(42)

You would not normally call any method with a double underscore 
pre/poist fix because they are special methods called by Python
itself. Thus when you do

A('foo')

Python actually calls two special methods on class A. First it calls the 
__new__() method to create an instance of A then it calls __init__() 
with 'foo' as argument to initialise that instance. You don't need to 
call init() directly. In fact it may even cause problems if you 
initialise a class twice.

So when you do

A('foo').__init__(42)

You actually do 3 things:
First you create a new instance of A, then you initialise it with 'foo' 
then you initialise it again with 42. In this case no harm is done 
because the init)() method just does a double assignment, losing the 
initial value. But if you were storing the data values in a lkist you 
would wind up with two values instead of one, which may not be a good thing.

> A(12).data

Here you create another instance of A and initialise it with 12 then you 
access its data attribute. If you do this in the interpreter the value 
of data will be printed, if you do it in a program nothing will happen.

In both iof the cases above the newly created instances will be garbage 
collected since they were not assigned to any variable.

> What are we actually calling this way?

You call the constructor __new__(), the initialiser __init__()
and you access a data item which calls the accessor __getattr__()

> Are there any other ways to get the same result?

It depends how you define 'the same results'.
The same end state can be achieved in several ways.
The same methods can be called in several ways, for example
you can call init via the class:

anAinstance = A('foo')
A.__init__(anAinstance, 42)

But in general all of these are a bad idea outside of
a class/method definition. Don't do it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list