Showing posts with label classes. Show all posts
Showing posts with label classes. Show all posts

February 12, 2010

New Python Class Available

I am happy to announce that the O'Reilly School of Technology have made the first of four Python classes available on their interactive teaching system. Students passing all four modules will be eligible to receive a Certificate for Professional Development from the University of Illinois' Office of Continuing Education.

The PSF has discussed certification schemes in the past, and the general feeling of the membership appeared to be against them. This may be true for high-level personnel and those with advanced degrees, but we should remember that Python will also be increasingly used by technicians and others whose formal educational background does not include a training in computer programming. I feel that a university-approved certification will be helpful at that level.

While many certifications aren't that meritorious, if a scheme requires proper practical experience and the training includes mentoring by live instructors or advisers rather than just the passing of a multiple-choice examination it can have some real value.

Time will tell, but I believe we will have passed a milestone once a university-accredited Python certification scheme is available. All I have to do now is write the other three courses ...

[NOTE: the author of this blog will receive royalties based on the number of students taking the classes mentioned in this article]

November 20, 2009

Starting 2010 With a Bang

Holden Web's first one-day workshop was, thanks to Jacob Kaplan Moss, a sell-out success. As a result, and partially due to some excellent feedback from the New York City Python Meetup group, we will be running the same workshop in New York on January 22, again with Jacob presenting. We are also offering a one-day IronPython workshop presented by Michael Foord on January 21.

Since the three-day Introduction to Python classes have been well-received in Virginia we are also offering that class in New York on January 18-20.

To try and make things easier for those attending and smooth out our administration we are using Eventbrite for the first time. I would really like to know how easy people find it to get information about our classes and to enroll for them. Anyone wanting specific information not mentioned in the course outlines is, of course, welcome to contact us for further details.

If you would like to take one of these classes simply follow the links above (or click here for a list of all our current offerings, then just go to the ones you are interested in) and click the Order Now button which should be clearly visible. Once you have entered the details click the Review Your Order button, and you have fifteen minutes to check that you have entered the correct information before you click the Pay Now button. It really couldn't be much easier, I hope.

We are also very interested to know what other event you would like us to run. This is the front end of a new venture for Holden Web, and your opinions and requirements (places you'd like to attend presentations as well as other topics) will help us to move in the right direction. So feel free to contact us with your suggestions, or make them in comments below. Thanks in advance for the feedback.

May 21, 2009

Factory Functions

In the last entry we discussed passing callables (using functions and classes) as arguments to functions, and calling them within the body of the function. This time we'll look at how functions can return more esoteric objects - again including functions and classes.

Beginners sometimes ask how a function can be made to return "more than one object". The strict answer is that it can't. The single object it returns can be a container, though, allowing several values to be extracted from the returned object. If you want a function to return three values the easiest way to arrange this is to have it return a three-element tuple, and then extract the individual values using an unpacking assignment. Here's a simple example.
def powers(a):
return a, a*a, a*a*a

a, square, cube = powers(10)
print(a, square, cube)
This prints 10 100 1000, showing that the three returned values have indeed been assigned to individual variables. Functions can return more complex objects than simple containers, though. A frequent example in the programming literature is a function that returns some newly-created function each time it is called. Typically the function returned will vary according to one or more of the arguments passed to the call that creates it.
def make_fun(power, debug=False):
def pow(x):
result = x ** power
if debug:
print("power(%s, %s) returned" % (x, power), result)
return result
return pow

squarer = make_fun(2)
cuber = make_fun(3, True)

print([f(9) for f in (squarer, cuber)])
A call to make_fun() results in a function being defined as make_fun's function body is being executed. This function (whose local name is pow) contains references to the arguments passed to make_fun, and is returned by the call to make_fun to be assigned and eventually called. The calls to the function are inside a list comprehension just because that's the easiest way to call a set of functions with the same argument(s).

The output from this is
power(9, 3) returned 729
[81, 729]
The debugging output from cuber is seen before the list comprehension because all calls have to return their values before the list comprehension is complete and ready for printing.

You may be familiar with the concept of a mixin class. Such classes are designed to take advantage of Python's multiple inheritance features to add functionality to any chosen classes, by creating a new class which is a subclass of both the mixin and the chosen class. You can see an exellent example of this in the socket library, where a ThreadingMixIn class is defined and can be used to extend the features of the basic UDPServer class like this:
class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
Note that the newly-declared ThreadingUDPServer class doesn't specify any behavior of its own, it merely inherits - first from the mixin and then from the base class, meaning that methods defined in the mixin take precedence over those defined in the base server class. One problem with this, however, is that it doesn't allow for any variation in the mixin classes - by the time you use them they are already created, and it's too late.

In the same way that we can parameterize functions, however, we can parameterize classes as well. Suppose we want to provide a trivial mixin to print the class's name in either upper- or lower-case. Not very inspiring, but the simplest example I could think of to get the point over, so please bear with me if you can think of simpler ways to do this. One possibility is this.
def mixin(cls, lcase=True):
class Mixin:
def nprint(self):
if lcase:
print(str(cls).lower())
else:
print(str(cls).upper())
class Result(Mixin, cls):
pass
return Result

class FirstClass:
pass

Cl1 = mixin(FirstClass, True)
cl1 = Cl1()
cl1.nprint()

mixin(FirstClass, False)().nprint()

Here the function first defines a mixin class, then creates a new class from the mixin and the base class provided as an argument. The interpreter cares not at all where the class definitions come from - classes are first-class objects just like functions and strings, and can just as easily be passed as function arguments as obtained any other way.

The output from the program, which I am sure you are waiting for with bated breath, is
<class '__main__.firstclass'>
<CLASS '__MAIN__.FIRSTCLASS'>
which shows that the program runs, and that the mixin class's behavior is conditioned by the function's second argument.

Now you might choose to argue that this isn't a very natural example, and I'd be inclined to agree with you. All I have to say besides that is, you try coming up with these examples and see how you like it. If anyone chooses to contribute a more natural example that can be expressed without too much extra code I'll be happy to write about it.

May 18, 2009

Simple Object Interactions

Here's a relatively simple piece of code that shows how easy it is to have Python objects interact. It's fairly standard stuff, so it probably won't be interesting to old hands, but if you haven't been using object-oriented programming very long then it might make a point or two.

Note that the code is in Python 3, though it will actually run on earlier versions, the printing will just be slightly different.
#
# Calling all reactive agents (with apologies to William Burroughs)
#
class Simulation:

def __init__(self, howmany):
self.agents = []
for i in range(howmany):
self.agents.append(Agent(self, i))

def showImportant(self, agent):
return "Agent: %d simulation: %d" % (agent.number, id(self))

def listAgents(self):
for a in self.agents:
a.showMe()

class Agent:

def __init__(self, sim, number):
self.sim = sim
self.number = number

def showMe(self):
print("Agent", self.number, "reporting:")
result = self.sim.showImportant(self)
print(result)

s = Simulation(3)
s.listAgents()
So, we start out with a class whose __init__() method is called with one argument, the number of agents to create. It creates a list of that many agents as its agents attribute. Note that when the Agent is created the Simulation instance passes itself as an argument to the Agent creator, and the Agent.__init__() method saves the reference to the Simulation instance as the Agent's sim instance variable.

Colloquially we could say that each Agent "knows" which Simulation it's a part of. So an Agent is able to call the methods of the simulation that it's a part of. This makes it possible to devise agents that call various simulation methods, and to incorporate them in several different simulations which implement those methods differently.

When building large data structures with this kind of pattern, by the way, it's important to note that the references are circular (simulations refer to agents, and agents refer to simulations). The garbage collector in older versions of Python would have real difficulties with structures such as the ones created in the code above. In essence it would say to itself "Well, I can't delete the simulation until I have deleted all the agents it refers to." Then it would look at all the agents, and for each one it would say to itself "I can't delete this until I have deleted the simulation it refers to". An unintelligent garbage collection might get stuck in an infinite loop here, but Python's garbage collector has never been that stupid.

Nowadays, I am happy to say, in Python 2 or 3 the collector is able to recognize these cyclic references and, as long as there are no references to such a structure from the outside, will (eventually) reclaim the space.

Next time we'll consider how a simulation might use several types of agents, still providing common behavior for them all.

November 10, 2008

Final "Introduction to Python" of 2008

As the year draws to a close Holden Web is pleased to remind readers that its final public "Introduction to Python" class of this year will be held from December 9-11 at our education center close to Washington, DC.

There are several hotels conveniently located within walking distance, and we provide breakfast snacks and lunch each day.

Purchase places on-line by credit card or using PayPal.

Thanks to all students who have already attended this class. We look forward to meeting you again as our range of course offerings increases.

July 29, 2008

One-Day Python Classes

Holden Web's third Introduction to Python class starts on September 9. It runs from Tuesday through Thursday, and I could easily use the training room for an extra day if I had a suitable topic for a one-day class. The question is, what would people want to learn? More specifically, what would they pay to come and learn?

I have a couple of ideas for popular topics, but your suggestions are also welcome. And since there's only over a month to go, better hurry! Thanks.

November 13, 2007

Training Plans

The demand for Python training is increasing by leaps and bounds, at least in the USA. This won't be a surprise to anyone who keeps an eye on the Python jobs board, since that makes it obvious that Python usage is growing quite rapidly (and not just in the USA).

As a result, Holden Web is planning a regular series of classes in the Washington DC area beginning February 2008. We have already identified a suitable venue, not far from National Airport and suitable for up to ten students.

If you have a current need for training, want to know what classes are currently available, or would simply like to let us know your requirements, please feel free to contact us. It's a juggling act to get public classes off the ground, and all information will be useful