Computer Science Canada [Python-tut] Classes: constructors, access, inheritance |
Author: | wtd [ Wed Apr 06, 2005 1:17 am ] | ||||||||||||||||||||
Post subject: | [Python-tut] Classes: constructors, access, inheritance | ||||||||||||||||||||
Let's construct a simple Name class as a demonstration. The class should have a constructor which takes two arguments. These are the first and last names. These become instance variables.
You'll notice the extra "self" argument in the constructor. All methods in a Python class take this argument, and it refers back to the object itself. You can call it anything you'd like, but "self" is the most common convention. As with everything Python, indentation denotes scope. Now, we can create a Name object and manipulate its instance variables.
Notice those last few lines. I was able to directly manipulate and change the last name quite easil from outside of the objecty. In object-oriented programming that's a big no-no. We generally want to encapsulate our data, and only allow the outside world to change it in very specific ways. So, how do we make the instance variable private? In Python this is accomplished by prepending the variable (or method) name with two underscores.
The last few lines are clearly showing that trying to access these instance variables from outside of the object is now impossible. Beautiful. Now, let's add a method to get a representation of the name as a string.
The only problem with this is that it doesn't follow Python convention. So instead we'll write the following, and
Inheritance is also critical to object-oriented programming. First off, let's create a NameWithTitle class that inherits from Name and create a new constructor that uses the base class constructor.
Now we can create a new NameWithTitle object.
You'll notice that it doesn't look like anything different has happened. Well, you'd be right. We have to override the __str__ method for that to happen.
And now, using it.
|
Author: | wtd [ Thu Apr 07, 2005 6:03 pm ] | ||||
Post subject: | A corollary | ||||
Determining at run-time if an object is of a particular type is quite easy. For this we use the isinstance function.
Further, we can get the name of an object's type with the type function.
|