You are a guest. Restricted access. Read more

Classes

In Python the basic elements of programming are things like strings, dictionaries, integers, functions etc. They are all objects. For example, every string object has a standard set of methods - some of which were used in Sect.strings.

In python one can create our own blueprints which can be used to create a user-defined objects. These are called classes.


class OurClass(object):
    """Class docstring."""
    def __init__(self, arg1, arg2):
        """Method docstring."""
        self.arg1 = arg1
        self.arg2 = arg2
    def printargs(self):
        """Method docstring."""
        print self.arg1
        print self.arg2

obj= OurClass('arg1', 'arg2')
print type(obj)
obj.printargs()

Here we define our own class”OurClass” using the class keyword. Methods are defined like functions - using the def keyword. They are indented to show that they are inside the class. In this example we create an instance of OurClass, and call it instance “obj”. When we create it, we pass in the arg1 and arg2 as arguments. When we call printargs() these original arguments are printed. The “init” method (init for initialize) is called when the object is instantiated. Instantiation is done by (effectively) calling the class.

obj= OurClass('arg1', 'arg2')

This creates a new instance is created. Then its “init” method is called and passed the arguments 'arg1' and 'arg2'.

Objects combine data and the methods used to work with the data. This means it's possible to wrap complex processes - but present a simple interface to them. Anyone using the object only needs to know about the public methods and attributes.

python/classes.txt · Last modified: 2013/04/14 16:52 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0