Python for Finance: Analyze Big Financial Data

(Elle) #1

Object Orientation


Wikipedia provides the following definition for object-oriented programming:


Object-oriented programming (OOP) is a programming paradigm that represents concepts as “objects” that have

data fields (attributes that describe the object) and associated procedures known as methods. Objects, which are

usually instances of classes, are used to interact with one another to design applications and computer programs.

This already provides the main technical terms that are also used in the Python world for


classes and objects and that will be made clearer in the remainder of this section.


Basics of Python Classes


We start by defining a new class (of objects). To this end, use the statement class, which


is applied like a def statement for function definitions. The following code defines a new


Python class named ExampleOne. This class does nothing but “exist.” The pass command


simply does what its name says — it passes and does nothing:


In  [ 1 ]:  class ExampleOne(object):
pass

However, the existence of the class ExampleOne allows us to generate instances of the


class as new Python objects:


In  [ 2 ]:  c   =   ExampleOne()

In addition, since this class inherits from the general object class, it already has some


batteries included. For example, the following provides the string representation of the


newly generated object based on our class:


In  [ 3 ]:  c.__str__()
Out[3]: ‘<__main__.ExampleOne object at 0x7f8fcc28ef10>’

We can also use type to learn about the type of the object — in this case, an instance of


the class ExampleOne:


In  [ 4 ]:  type(c)
Out[4]: __main__.ExampleOne

Let us now define a class that has two attributes, say, a and b. To this end, we define a


special method called init that is automatically invoked at every instantiation of the class.


Note that the object itself — i.e., by Python convention, self — is also a parameter of this


function:


In  [ 5 ]:  class ExampleTwo(object):
def __init__(self, a, b):
self.a = a
self.b = b

Instantiating the new class ExampleTwo now takes two values, one for attribute a and one


for attribute b. Note in the preceding definition that these attributes are referenced


internally (i.e., in the class definition) by self.a and self.b, respectively:


In  [ 6 ]:  c   =   ExampleTwo( 1 , ‘text’)

Similarly, we can access the values of the attributes of the object c as follows:


In  [ 7 ]:  c.a
Out[7]: 1
In [ 8 ]: c.b
Out[8]: ‘text’
Free download pdf