Defining a Class
When you are considering how even small programs of a few hundred lines of Python code is working, you will often realize that the programs are keeping track of data in groups — when one thing is accessed, it affects other things that need to go along with it. Almost as often, you ’ ll realize that you have whole lists of this interdependent data — lists in which the first element in list1 is matched to the first element in list2 and list3, and so on. Sometimes this can and should be solved by combining the lists creatively. Python employs the concept of creating an entire class of code that acts as a placeholder. When a class is invoked, it creates an object bound to a name.
class Fridge: """This class implements a fridge where ingredients can be added and removed individually, or in groups."""
Consider the following program for demonstration
>>> class name1(): def setmyname(self,myName): self.name = myName >>> jiname = name1() >>> jiname.setmyname("Jim") >>> print jiname.name Jim
Note some points about Python ’ s implementation of class programming as demonstrated in the preceding example:
1) If we were inheriting from other classes, those class names would have been inside the parentheses of the class name1(): definition.
2) In this case, there is one class method, setmyname . If we wanted to create a constructor for the class, it would be named _init__ .
3) To create an instance of a class, you simply assign a variable to the class definition, as in jimname = name1() .
4) Attributes are accessed with familiar dot notation ( instance variable.attribute ) such as jimname.name .