A class is similar to both a factory and a blueprint in that it makes copies of itself—but the copies are what do the actual work. Here is an example of a class:

class SayMyName:

def init (self, myname): self.myname = myname def say(self):

print "Hello, my name is", self.myname

You use a class to create objects called instances that can do specific things. This code creates an instance of the SayMyName class:

name1 = SayMyName("Aahz")

An instance has access to the class's methods (which are just functions attached to a class). This code applies the say() method to the name1 instance:

Classes are useful because they can combine both data and methods that operate on that data. Python's data types—lists, strings, and so on—are based on classes.

Was this article helpful?

0 0

Post a comment