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.python: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.