See All Titles |
![]() ![]() Python Classes and InstancesIn Python, a class is a user-defined data type, and as in most other languages, you define Python classes using the keyword class. class <class name>: <class statements> The class statements section contains any valid Python statement that defines class constants or class methods. Note that the contents of the variable namespace formed by executing the commands in the class statement make up the class dictionary. Two ways to create classes are
A class definition starts at the keyword class and ends at the last line of the indented block of code that goes underneath. Methods and class constants define a class namespace. Usually, a class has several methods, and they must all start with the keyword def. All methods have the additional argument self as the first argument in the method header—The convention is to call it self because it could be any other name. Python's self argument is similar to the this keyword in C++. Its function is to transport a reference of the object in a way that when a method is called, it knows which object should be used. >>> class a: … def __init__(self): … print self … >>> b = a() >>> b <__main__.a instance at 795420> In order to reference an attribute within a class, you need to use either self.attribute or classname.attribute. Note that the self.attribute syntax is to remove ambiguities between instance variables and function local variables. Also, self.attribute and classname.attribute are different. The second sets class attributes, which will affect all instances of the class. >>> class c: … def __init__(self, value=None): … self.name = value … To reference an attribute while using a class instance, you have to use instancename.attribute. >>> obj.name A class can also contain class variable assignments. These variables are shared by all the class instances. Class variables are useful when the assignment of default values to instances is required. Class variables do not have the self. prefix. For example >>> class Student: … default_age = 20 # class variable … def __init__ (self): … self.age = Student.default_age # instance variable Note that in the previous example, we had to use Student.default_age instead of using only default_age because the global namespace for a method is the module in which it was defined—not the class namespace. The next example creates an instance variable that has the same name of the class variable. >>> class Student: … default_age = 20 # class variable … def __init__ (self, age): … self.default_age = age # instance variable Suppose that you have the following code stored in a file called c:\ python\ studentfile.py. This code defines three different variables named default_age (at lines 2, 4, and 9). 1: class Student: 2: default_age = 20 # base class variable 3: def __init__(self, age): 4: self.default_age = age # base class instance variable 5: 6: class Newstudent(Student): 7: "New student class" 8: def __init__(self, age=20): 9: self.default_age = age # instance variable The following code imports the previous module. Which variable is being used by the instance call at line 5? 1: >>> import sys 2: >>> sys.path = sys.path + ['c:\ \ python'] 3: >>> import studentfile 4: >>> Joao = studentfile.Newstudent(15) 5: >>> Joao.default_age 6: 15 Tip
In order for Python to find your modules, the directory where you save them must be an entry of the sys.path list. The answer is the instance variable of the newstudent class (line 9 from the first listing). In cases like this, the search order is defined as
The following variation is slightly different than the previous code. This example shows what you need to do to make the class Newstudent call the superclass's __init__ method. 6: class Newstudent(Student): 7: "New student class" 8: def __init__(self): 9: Student.__init__(self, Student.default_age) Note that we are calling the __init__ method of the Student class (the superclass). The class constant Student.default_age is also used in this example. It is important to say that when calling unbound methods (methods that are not tied to an instance) like this one, you must explicitly say that the first argument is self. 1: >>> Joao = studentfile.Newstudent() 2: >>> Joao.default_age 3: 20 Attributes of a ClassNext, I list the attributes that classes expose to programmers.
The Python Class BrowserThe pyclbr module offers you the possibility of browsing all the information about classes that is stored in a specific module. readmodule()This function reads the module and returns a dictionary in the format { classname:classinfo}, where classinfo is an instance object of the class. basic syntax: variable = pyclbr.readmodule(module) >>> import pyclbr >>> moduletobrowse = pyclbr.readmodule("profile") >>> for classname, classinfo in moduletobrowse.items(): … print "Class name: %s" % classname … Class name: HotProfile Class name: OldProfile Class name: Profile or, if you use our student example >>> import pyclbr >>> moduletobrowse = pyclbr.readmodule("studentfile") >>> for classname, classinfo in moduletobrowse.items(): … print "Class name: %s" % classname … Class name: student Class name: newstudent If you need to go deeper than that, you can look at the classinfo object. Python InstancesEach instance defines its own namespace of data, and it inherits behavior from the class (and possible base classes) that have originated it. In order to create a new instance of a class, you just need to say newinstance = classname() Suppose that you have a Person class like this class Person: def __init__(self, name): self.name = name self.family = [] def addmember(self, member): self.family.append(member) For example, if you want to create a new instance of the chef class, you must type: >>> anthony = Person() You can also pass arguments to the __init__ function of the class. These arguments can be used to set the initial values of an object. Let's see how it works. >>> anthony = Person("anthony") To call the methods of a class, you have to use the dot notation: >>> anthony.addmember("son") You also need to use the dot notation to have access to variables (attributes) of each instance. >>> anthony.family ["son"] An interesting detail about Python object attributes is that they don't need to be declared inside the class before they get used because they can be created dynamically. >>> class DummyClass: … pass … >>> colors = DummyClass() >>> color.alarm = "red" The next example dynamically creates multiple attributes for the colors instance. >>> class record: … def __init__(self, **args): … self.__dict__.update(args) … >>> colors = record(alarm="red", normal="green") >>> colors.normal 'green' isinstance() and issubclass()The built-in functions isinstance() and issubclass() are always available without the need for importing any module because they are part of the __builtin__ module. isinstance()This function tests whether an object is an instance of a class. It returns 1 if the object is an instance. Otherwise, it returns 0. Note that this function handles subclass relationships as well—for instance, isinstance(subclassinstance, superclass) returns true. basic syntax: isinstance(instance_object, class_object) >>> class a: … pass … >>> inst = a() >>> isinstance(inst,a) 1 As you can see next, you can also use this function to identify the object's type. Note however, that this is behavior that works for non–instance objects. Floats and ints act quite differently from Python class instances (for instance, there is no way to subclass types.IntType). >>> import types >>> isinstance(3, types.IntType) 1 >>> isinstance(3, types.FloatType) 0 issubclass()This function returns 1 if the class object classobj1 is a subclass (derived class) of the class object classobj2. basic syntax: issubclass(classobj1, classobj2) >>> class a: … pass … >>> class b(a): … pass … >>> issubclass(a,b) 1 Instance Attributes
|
© 2002, O'Reilly & Associates, Inc. |