[Tutor] Understanding Classes

Alan Gauld alan.gauld at btinternet.com
Mon Jan 20 10:33:29 CET 2014


On 20/01/14 00:55, Christian Alexander wrote:
> I would first like to state two things, those being that I am a horrible
> writer as well as explaining things, but Ill try my absolute best.
>   Everything python is an object.  Strings, integers, lists, so on and
> so forth.  In regards to classes and their relativity towards objects, I
> am at complete standstill.

OK, we need to backup a little.

Objects are the individual instances of data that we work with.
This individual strings like 'foo' and 'hello' are objects.
Strings in general are a class. 'foo' and 'bar' are instances of that 
class, or objects of that class. (instance and object are almost synonymous)

Similarly for integers. 3,5,97 and 123456789 are all instances
of the integer class.

Of course these are built in classes of object so you don't see an 
explicit class defined anywhere. But classes that you define are just 
like those built in types. You define the structure and behaviour in the 
class and create instances of it to work with as objects.

> However, I understand that classes are
> parallel to that of a blueprint,

Yes, they define what the objects will look like, what data and what 
methods they contain. But to use those objects you have to instantiate 
them and its there that the usage varies slightly from the built in types:

For built in string type objects you do this

mystring = 'a new string object'

But if String were a user defined class you'd need to do this:

mystring = String('a user defined string object')

ie. you'd 'call' the class name with the data arguments needed.
In fact in Python you can explicitly call str() if you really
want to, missing it out is a convenience.

After that initial object creation you would use mystring identically 
regardless of whether it was user defined or built in. So we can call 
methods of the class using the instance like:

mystring.upper()
mystring.split()

etc

Do you follow things so far? It's important to understand the usage of 
classes and objects before we start worrying about the internal
details.

-- 
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