[Tutor] Understanding Classes

David bouncingcats at gmail.com
Mon Jan 20 11:59:02 CET 2014


On 20 January 2014 20:33, Alan Gauld <alan.gauld at btinternet.com> wrote:
> 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.
>
> 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()

And Christian you can experiment with Alan's examples interactively
by running the Python interpreter, for example:

$ python
Python 2.7.3 (default, Jan  2 2013, 16:53:07)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> mystring = 'a new string object'
>>> type(mystring)
<type 'str'>
>>> mystring.upper()
'A NEW STRING OBJECT'
>>> 'another new string'.upper()
'ANOTHER NEW STRING'
>>> 'yet another string'.split()
['yet', 'another', 'string']

>>> exit()

Typing in the first >>> line
>>> mystring = 'a new string object'
creates a string object.

Typing in the next >>> line
>>> type(mystring)
shows that mystring is of type str, which is the built in class for
strings. So the mystring object is an instance created from class str.

Typing in the next line
>>> mystring.upper()
shows that the mystring object possesses a built in method named
upper() that knows how to return an upper case copy of itself.

Typing in the next line
>>> 'another new string'.upper()
shows that any/every string knows how to do the same thing. Because
every string has the same method named upper(). Because every string
instance is created from the str class, and the str class defines
upper(), so every string inherits this method.

Typing in the next line
>>> 'yet another string'.split()
shows that any/every string has a method named split() that knows how
to return a list of individual words in the string. This method is
also defined by the str class, and so is inherited by every string.

> Do you follow things so far?


More information about the Tutor mailing list