Home arrow Python arrow Page 4 - More Object Orientation in Python

Methods: Instance, Class and Static - Python

This article goes beyond the basics of object orientation in Python. It covers the interesting things you can do with new-style classes, including properties and attributes, as well as other useful information.

TABLE OF CONTENTS:
  1. More Object Orientation in Python
  2. Types and Classes
  3. Properties
  4. Methods: Instance, Class and Static
By: Peyton McCullough
Rating: starstarstarstarstar / 11
December 06, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Let's take a simple class and build a simple object from it:

>>> class SimpleClass:
 def simpleMethod ( self ):
  return True


>>> simpleObject = SimpleClass()

So, basically, we have the class SimpleClass and an instance of that class, simpleObject. Let's say we want to call the method simpleMethod. We cannot do so by calling the method in the context of the class, or we get an error:

>>> SimpleClass.simpleMethod()

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in -toplevel-
    SimpleClass.simpleMethod()
TypeError: unbound method simpleMethod() must be called with SimpleClass instance as first argument (got nothing instead)

This is because simpleMethod is an instance method. Each instance of SimpleClass has the method, and the method of one instance is called independently. On the other hand, we have static methods and class methods, which do not have relationships with the instances of their class. Let's take a look at static methods first. Declaring one is very straightforward:

>>> class StaticTest:
 def staticExample ( number ):
  return number ** .5
 staticExample = staticmethod ( staticExample )

Before we continue, notice that what we have created is not a new-style class. Static methods and classes work with old-style classes and new-style classes.

Now, try calling the staticExample method:

>>> StaticTest.staticExample ( 25 )
5.0

As you can see above, the method we created can be called within the context of our class. No instance is involved anywhere in the process, and the self variable is not present. Neither is the cls variable, however, so we are not able to do anything special to the class. This shortfall can be addressed by using class methods, which are equally as easy to create. Let's let a class, PythonBurgers, represent a chain of restaurants. For the chain of restaurants, we want to keep track of how many hamburgers have been sold. With class methods, we can do this in a nice, object-oriented way:

>>> class PythonBurgers:
 hamburgers = 0
 def sellHamburgers ( cls, amount = 1 ):
  cls.hamburgers = cls.hamburgers + amount
 sellHamburgers = classmethod ( sellHamburgers )

Now we're ready to sell ourselves the first hamburger of our business. We can call the method sellHamburgers in the context of the PythonBurgers class:

>>> PythonBurgers.sellHamburgers ( 2 )
>>> PythonBurgers.hamburgers
2

As joint owners of a chain of restaurants, we've consumed two hamburgers. However, since we want a chain of restaurants, it makes sense to offer entrepreneurs the chance to open franchises. Each franchise will be a little different, but they will share the same parent:

>>> franchise1 = PythonBurgers()
>>> franchise2 = PythonBurgers()
>>> franchise3 = PythonBurgers()

Now let's have each franchise sell some hamburgers:

>>> franchise1.sellHamburgers ( 11 )
>>> franchise2.sellHamburgers ( 48 )
>>> franchise3.sellHamburgers ( 35 )

The result is as follows:

>>> PythonBurgers.hamburgers
96


Since our class method belongs to a class instead of its instances, it affects the class and not its instances. This behavior is pretty interesting.

Conclusion

While you may have noticed a gap between types and classes in earlier versions of Python, Python 2.2 has managed to bridge the gap, allowing built-in types to be subclassed and extended in ways that were not previously possible. Python 2.2 has also brought other changes to object orientation in Python, with one of the changes being properties. Properties allow the way in which attributes are set and retrieved to be easily governed. This can insure that the values coming into an object make sense, and it allows the object to format values retrieved.

The other change we have covered is static methods and instances. Instead of being specific to a particular instance, static and class methods are related to the class in which they are defined. This allows new tasks to be completed in an object oriented way.



 
 
>>> More Python Articles          >>> More By Peyton McCullough
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: