[Tutor] Understanding Classes
Alan Gauld
alan.gauld at btinternet.com
Tue Jan 21 11:04:18 CET 2014
On 21/01/14 04:20, Christian Alexander wrote:
> class Person:
> def __init__ (self, name, age): # is self just a
> placeholder for an arbitrary object?
Yes. If you create say 4 persons, John, Paul, Ringo and George.
When you call any method on those people objects the same code
in the Person class will get executed. So that method code needs some
way to know which object is being manipulated. That's all that self is,
a reference to the object currently being worked on.
> How does __init__ actually work?
__init__() is actually just an ordinary metjod like any other.
There is no magic in the method itself. It is a function that takes in
arhguments (self, name, age in this case) and processes them (stores
them in the self object).
The magic happens when the Class is instantiated.
So if we create a person object like this:
paul = Person("Paul", 71)
Python first creates a new empty object in memory then passes that
object to Person.__init() with the arguments (paul, "Paul", 71).
The end result is an instance called paul pre-populated by the arguments
that we passed to Person.
We can do that manually by not defining __init__()
class Person2:
def setData(self, name, age):
self.name = name
self.age = age
paul = Person2() # get a new empty Person2 object
paul.setData("Paul", 71) # do the equivalent of __init__
print (paul.Name, paul.age)
> self.name <http://self.name/> = name # why
> assign name to self.name <http://self.name> variable?
Remember that name is the input parameter to the method.
Just like any other function the input parameters are just
temporary variables that get thrown away at the end of
the function. We want to store those values in our new
instance. So we assign them to a data attribute of the
new object(self) for storage so that we can access them
in the future. For example the salute() method accesses
the self.name attribute. It can only use that if it has
been stored previously.
We can add attributes to an object at any time in Python.
For instance, using our paul example above we can do this:
paul.instrument = "bass"
and later print paul.instrument.
The equivalent of doing that inside a method is to use self.
So we could have another method in Person like this:
class Person:
def __init__(self, name, age):....
def salute(self):....
def joinBand(self, instrument):
self.instrument = instrument
and we can call that method as before
paul = Person("Paul", 71)
paul.joinBand("bass")
So setting attributes can be done anywhere and from
any method it's not special to init. But because init
gets called automatically when we first create the
object it's convenient to be able to set the initial
values at the same time as we create the object.
Is that helping?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list