Objects



One of the key aspects of Python is that the language is Object Oriented (OO). The  OO paradigm is a conceptual and organizational methodology that we use to create reusable code and develop applications efficiently. Objects are not inherently complex or difficult to work with, in fact, they are simple to create and re-use throught our programming endeavours. 

Objects have two main characteristics:

  • methods
  • attributes

Methods are another word for functions contained within an object. Attributes are variables within an object. Consider my toaster:

>>> my_toaster = Toaster('shiny', 'crispy')
>>> my_toaster.make_toast(bread)
# returns toast.
>>> my_toaster.color
silver
>>> my_toaster.darkness_setting
crispy

In the first line, I create an instance of the Toaster class (notice the capital T in Toaster) and assign it to 'my_toaster'. I tell the Toaster class that my_toaster is shiny and makes crispy toast. Afterwords, I can interact with my_toaster by accessing its methods (functions) and attributes (variables).

Notice that the function and attributes are accessed by appending a dot ('.') and the relevant name/function call. This is called, appropriately, 'dot notation' and is designed as a convenience for us programmers.

So, creating an instance of a class seems easy, right? Lets cover the basics of creating a class. We will go ahead and peer inside the Toaster class.

class Toaster:
"""Found in kitchens around the world. Excellent for toasting bread."""
    def __init__(self, color, darkness_setting):
        self.color = color
        self.darkness_setting = darkness_setting
       
    def make_toast(bread):
            # Code to make toast
            return toast

The first line above is the class definition. The word class preceeds the name (uppercase as a convention) and a colon. The following line is a documentation string, giving further details about the toaster class.

The __init__() method is called a class constructor. Python calls the __init__() method whenever a class instance is created. In this case, the __init__() method simply assigns values to color and darkness_setting attributes  for the instantiated class, referenced by self. Python instances use the self keyword  to refer to their internal state.

Next, we define the make_toast() function, which takes one parameter, named bread. The make_toast() function is nested within the Toaster class and is therefore a method of Toast, rather than simply being a function. make_toast() would normally have some additional code to process the input data, but we can simplify things for this example.

The last thing that the make_toast() method does is return the toast object (yes, this too is an object). When an object returns data, the data may be assigned to a variable for later use.

>>> our_toaster = Toaster('turquois', 'high heat')
>>> snack = our_toaster.make_toast(wheat_bread)
>>> myself.eat(snack)

Further Reading

Task

  1. Think of two objects that you would encounter in your daily experience, other than toasters :-)
  2. List several attributes for each object
  3. List at least one method that the object employs
  4. Create Python pseudocode for each object, don't forget the __init__() function.
  5. Post your pseudo code to this task discussion.

Extra Credit: Have one of the objects return information that is utilized by the other object. 

Task Discussion


  • Fer said:

    Second class Shocks() is taking parameters from original Rallycars()
    Rallycars determines the minimum permissible weight according to regulations for every category.
    According to the data contained in Rallyclass, Shocks() will let the team know which suspension system should be installed for each kind of car.
    on Nov. 13, 2013, 6:14 a.m.
  • Wouter Tebbens said:

    I've taken two objects: Car and GasStation and instead of pseudocode I wrote the two classes with some attributes and methods as follows: http://pastebin.com/kDtFJSbj The code runs as you can try/see.

    When a car is instantiated and a gas station, we can send the car to the station to get fuel from that station for the gas station's price, and at the same time it  calls the car's calculate_fuel method to calculate the new fuel level.

    Clearly this is a very simple example code; it would be good to convert the fuel price into a dictionary, add methods for driving and consuming the fuel as well ,-)

    One thing that doesn't work, and I couldn't yet figure out why, is the fuel level and price seem to be treated as integers, and don't multiply correctly. However I tried to make them floats, but no idea yet why that doesn't seem to be effective. Any ideas?

    on April 7, 2013, 11:21 a.m.
  • saravanan said:

    class Mouse:
        def __init__(self,cursor,move_cursor,x,y,speed):
            self.cursor=cursor
            self.move_cursor=initpos_move_cursor
            self.x=x_pixels
            self.y=y_pixels
            self.speed=speed
        def click(self,lclick,rclick):
            self.lclick=lclick
            self.rclick=rclcik
        def mousewheel(self,scrollup,scrolldown):
            self.scrollup=scrollup
            self.scrolldown=scrolldown

     

    on Sept. 23, 2012, 1 a.m.
  • Mars83 said:

    """
    Created on 12.09.2012
    
    @author: Mars83
    
    Task
    
    1. Think of two objects that you would encounter in your daily experience, other than toasters :-)
    2. List several attributes for each object
    3. List at least one method that the object employs
    4. Create Python pseudocode for each object, don't forget the __init__() function.
    5. Post your pseudo code to this task discussion.
    Extra Credit: Have one of the objects return information that is utilized by the other object. 
    
    """
    
    class Car():
        """ A car is a special vehicle. """
        def __init__(self, manufacturer, name, current_speed, top_speed, direction, color, horn, mileage, price, year_of_manufacture, kW, current_position):
            """ Cctor of Car. """
            self.manufacturer = manufacturer
            self.name = name
            self.current_speed = current_speed
            self.top_speed = top_speed
            self.direction = direction
            self.color = color
            self.horn = horn
            self.mileage = mileage
            self.price = price
            self.year_of_manufacture = year_of_manufacture
            self.kW = kW
            self.current_position = current_position
            
        def drive(self, acceleration, direction):
            """ Drive and accelerate the car in a stated direction. """
            self.direction = direction
            self.current_speed += acceleration
            current_position = self.current_position
            # ...
            return current_position
            
    class Game():
        """ Games are leisure time activities which can be played by several players. """
        def __init__(self, name, game_type, min_players, max_players, victory_condition):
            """ Cctor of Game. """
            self.name = name
            self.game_type = game_type
            self.min_players = min_players
            self.max_players = max_players
            self.victory_condition = victory_condition
            
        def play(self, *players):
            """ Play a game. """
            count = 0
            winner = None
            for player in players:
                count += 1
            # ...
            return winner
    
    on Sept. 12, 2012, 8:29 a.m.
  • ionut.vlasin said:

    class Pc():
        def __init__(self):
            self.lcdAvailable=True
            self.mouseAvailable=True
            self.keyboardAvailable=True
            self.mozillaInstaled=False
        def internetBrowser(self):
            self.mozillaInstaled=True
            return self.mozillaInstaled
    class InternetConnection():
        def __init__(self):
            self.connection=True
        
          

     

    on July 11, 2012, 7:38 a.m.
  • gnuisance said:

    #!/usr/bin/env python
    # Author: gnuisance
    # Practice Python Classes

    class Tv():
        def __init__(self):
            self.power = 'off'
        def on(self):
            self.power = 'on'
            return self.power
        def off(self):
            self.power = 'off'
            return self.power

    class Remote():
        def __init__(self):
            pass
        def power(self):
            if tv.power is 'off':
                tv.power = 'on'
                return tv.power
            if tv.power is 'on':
                tv.power = 'off'
                return tv.power

    tv = Tv()
    remote = Remote()
                
    while True:
        try:
            toggle = raw_input('')
        
        except KeyboardInterrupt:
            exit()
                
        if toggle.strip() == 'exit':
            break
        print remote.power()

    on April 16, 2012, 7:14 a.m.