Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Python-tut] Classes: constructors, access, inheritance
Index -> General Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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.

code:
class Name:
   def __init__(self, first, last):
      self.first = first
      self.last = last


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.

code:
>>> class Name:
...    def __init__(self, first, last):
...       self.first = first
...       self.last = last
...
>>> bob = Name("Bob", "Smith")
>>> bob.first
'Bob'
>>> bob.last = "Johnson"
>>> bob.last
'Johnson'
>>>


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.

code:
>>> class Name:
...    def __init__(self, first, last):
...       self.__first = first
...       self.__last = last
...
>>> bob = Name("Bob", "Smith")
>>> bob.__first
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: Name instance has no attribute '__first'
>>> bob.__last
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: Name instance has no attribute '__last'
>>>


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.

code:
class Name:
   def __init__(self, first, last):
      self.first = first
      self.last = last
   def to_string(self):
      return self.__first + " " + self.__last


The only problem with this is that it doesn't follow Python convention. So instead we'll write the following, and

code:
class Name:
   def __init__(self, first, last):
      self.__first = first
      self.__last = last
   def __str__(self):
      return self.__first + " " + self.__last


code:
>>> bob = Name("Bob", "Smith")
>>> str(bob)
'Bob Smith'
>>> print bob
Bob Smith
>>>


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.

code:
class NameWithTitle(Name):
   def __init__(self, title, first, last):
      Name.__init__(self, first, last)
      self.__title = title


Now we can create a new NameWithTitle object.

code:
>>> bob = NameWithTitle("Dr.", "Bob", "Smith")
>>> str(bob)
'Bob Smith'
>>> print bob
Bob Smith
>>>


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.

code:
class NameWithTitle(Name):
   def __init__(self, title, first, last):
      Name.__init__(self, first, last)
      self.__title = title
   def __str__(self):
      return self.__title + " " + Name.__str__(self)


And now, using it.

code:
>>> bob = NameWithTitle("Dr.", "Bob", "Smith")
>>> str(bob)
'Dr. Bob Smith'
>>> print bob
Dr. Bob Smith
>>>
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: 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.

code:
>>> isinstance("hello", str)
True
>>> isinstance([1,2,3], list)
True
>>> isinstance({'f': 'g'}, list)
False
>>>


Further, we can get the name of an object's type with the type function.

code:
>>> type(42)
<type 'int'>
>>>
Display posts from previous:   
   Index -> General Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: