[Tutor] Class vs. instance

Dave Angel d at davea.name
Wed Jan 18 03:34:42 CET 2012


On 01/17/2012 09:13 PM, Stayvoid wrote:
> Hello!
>
> Here is another one.
>
> 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)
> A(12).data
>
> What are we actually calling this way?
> Are there any other ways to get the same result?
The first line creates an instance of class A, then immediately calls 
the method __init__() as though it were a normal function.  It then 
discards the object.

You should only call __init__() from within another class' __init__().  
It's called automatically when an object is created;  leave it at that.

You also usually want to keep the instance around, and use it more than 
once.  Otherwise you could just use ordinary functions and dispense with 
the confusion.

A(12) creates an object, then you reference the data attribute of that 
object, then you throw them both out.  Not much use there either.

Try  something like:

obj= A(49)
print obj.data
obj2 = A("artichoke")
obj.data = 99
print obj.data
print obj2.data

Two more things.  Remove the print statement from methods like 
__init__(), unless it's just for debugging purposes.  And add a base 
class of object to your class definition, so that a new-style class is 
created.  When you get to more advanced usage, it'll make a difference, 
and you might as well use the version of class that'll still work in 
Python 3.x.

class A(object):
      .....



-- 

DaveA



More information about the Tutor mailing list