[Tutor] Understanding Classes

Steven D'Aprano steve at pearwood.info
Tue Jan 21 12:32:53 CET 2014


On Mon, Jan 20, 2014 at 09:33:29AM +0000, Alan Gauld wrote:

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

Just to be clear here, the difference is a simple matter of syntax. 
Because strings are so common in programming, Python gives you special 
syntax for creating strings. When you have code like this:

'a new string object'

Python still has to create a string object, exactly the same as with a 
custom class. The only difference is that creating strings is handled 
automatically, by the Python interpreter, rather than by you having to 
create your own String class. (Of course you can create a string class 
if you so wish.)


-- 
Steven


More information about the Tutor mailing list