Sunday, April 25, 2010

Some OO Concepts in Python

PRIVATE VS PUBLIC

the short answer is no - in other words, this is not productively supported.

use the convention of prefixing 'would otherwise be private if the dumb language supported it' fields with an underscore, e.g.

class TheClass:

def __init__(self):
self._nominallyPrivateField = 'private'

CLASS vs INSTANCE OBJECTS

Class Objects support
- instantiation
- attribute referencing

class TheClass:

classLevelField = 'class level field'

def __init__(self):
self.instanceLevelField = 'instance level field'


Making our descriptively named class more accurately self-referential:

class TheClass:

classLevelField = 'class level field'

def __init__(self):
self._nominallyPrivateInstanceLevelField = 'only nominally private instance level field'

Finally, just to avoid any lurking confusion, THE FOLLOWING IS FLAWED

class TheClass:

classLevelField = 'class level field'

self._nominallyPrivateInstanceLevelField = 'only nominally private instance level field'

def __init__(self):
pass

and fails miserably, raising a NameError exception;

NameError: name 'self' is not defined


-------

So, annotating a method with the @classmethod produces something quite similar to a C# static method. In other words, within the class method only local and class level references are possible, or rather, no instance level field or method is accessible (short of instantiating an object of that class within the class method, and calling the method on that instance).

Where C# and python differ, however, is that in C# to call the static method DoStuff() on class TheClass, you would have something like this

TheClass.DoStuff()

In other words, you can't have something like this, where you call the class method on an instance variable

TheClass myClass = new TheClass();
myClass.DoStuff();

The compiler will kick you in the head.

In python, however, there is no such limitation. You can happily call a class method on an instance variable (the class method still won't have access to the instance level scope).

ABSTRACT BASE CLASSES & QUASI-INTERFACES
- ABCs - PEP 3119 = http://www.python.org/dev/peps/pep-3119/
- from the pythondocs: http://docs.python.org/library/abc.html
- James Tauber's take on interfaces: http://jtauber.com/blog/2007/03/04/interfaces_versus_abstract_base_classes_in_python/

No comments:

Post a Comment

comment: