<jupyter_start><jupyter_text>Python for Finance (2nd ed.)**Mastering Data-Driven Finance**&copy; Dr. <NAME> | The Python Quants GmbH  Object Oriented Programming* Class: An abstract definition of a class of objects. For example, a human being.类* Object: An instance of a class. For example, Sandra.对象* Attribute: A feature of the class (class attribute) or of an instance of the class(instance attribute). For example, being a mammal, being male of female, or color of the eyes.属性* Method: An operation that the class can implement. For example, walking.方法* Parameters: Input taken by a method to influence its behavior. For example, three steps.参数* Instantiation: The process of creating a specific object based on an abstract class.实例化  Introduction<jupyter_code># A simple class implementing the example of a human being might look as follows.

class HumanBeing(object):  
    def __init__(self, first_name, eye_color):  
        self.first_name = first_name  
        self.eye_color = eye_color  
        self.position = 0  
    def walk_steps(self, steps):  
        self.position += steps  
HumanBeing.
Sandra = HumanBeing('Sandra', 'blue')  ##类的实例化
Sandra.first_name  
Sandra.position  
Sandra.walk_steps(5)  
Sandra.position  
Sandra.walk_steps(-5)
Sandra.position<jupyter_output><empty_output><jupyter_text>A Brief Look at Standard Objects  int<jupyter_code>n = 5  
n.numerator?
type(n)  
n.numerator  
n.bit_length()  
n + n  
2 * n  
n.__sizeof__()<jupyter_output><empty_output><jupyter_text>list<jupyter_code>l = [1, 2, 3, 4]  
type(l)  
l[0]  
l.append(10)  
l + l  
2 * l  
sum(l)  
l.__sizeof__()<jupyter_output><empty_output><jupyter_text>ndarray<jupyter_code>import numpy as np  
a = np.arange(16).reshape((4, 4))  
a  
type(a)  
a.nbytes  
a.sum()  
a.cumsum(axis=0)  
a + a  
2 * a  
sum(a)  
np.sum(a)  
a.__sizeof__()<jupyter_output><empty_output><jupyter_text>DataFrame<jupyter_code>import pandas as pd  
df = pd.DataFrame(a, columns=list('abcd'))  
type(df)  
df.columns  
df.sum()  
df.cumsum()  
df + df  
2 * df  
np.sum(df)  
df.__sizeof__()<jupyter_output><empty_output><jupyter_text>Basics of Python Classes<jupyter_code>class FinancialInstrument(object):  
    pass  
fi = FinancialInstrument()  
type(fi)  
fi  
fi.__str__()  
fi.price = 100  
fi.price  
class FinancialInstrument(object):
    author = '<NAME>'  ##class级别的属性，可以被下面任何的instance继承
    def __init__(self, symbol, price):  ##实例化的属性
        self.symbol = symbol  
        self.price = price  
FinancialInstrument.author  
aapl = FinancialInstrument('AAPL', 100)  
aapl.symbol  
aapl.author  
aapl.price
aapl.price = 105  ##实例化的属性可以随意更改
aapl.price  
class FinancialInstrument(FinancialInstrument):  ##新的子类继承父类的所有属性和方法
    def get_price(self):  
        return self.price  
    def set_price(self, price):  
        self.price = price  
fi = FinancialInstrument('AAPL', 100)  
fi.
fi.get_price()  
fi.set_price(105)  
fi.get_price()  
fi.price  
class FinancialInstrument(object):
    def __init__(self, symbol, price):
        self.symbol = symbol  
        self.__price = price  ## Price is defined as a private instance attribute 私有化属性
    def get_price(self):
        return self.__price
    def set_price(self, price):
        self.__price = price
fi = FinancialInstrument('AAPL', 100)
fi.get_price()  
# causes intentional error
fi.__price  ##私有化属性，无法调用
fi.
## If the class name is prepended with a single leading underscore, direct access and manipulation are s
fi._FinancialInstrument__price  ##调用私有属性方法
fi._FinancialInstrument__price = 105  
fi.get_price()
fi.set_price(100)  
class PortfolioPosition(object):
    def __init__(self, financial_instrument, position_size):
        self.position = financial_instrument  
        self.__position_size = position_size  
    def get_position_size(self):
        return self.__position_size
    def update_position_size(self, position_size):
        self.__position_size = position_size
    def get_position_value(self):
        return self.__position_size * \
               self.position.get_price()  
pp = PortfolioPosition(fi, 10)
pp.get_position_size()
pp.get_position_value()  
pp.position.get_price()  
pp.position.set_price(105)  
pp.get_position_value()  
pp.position.<jupyter_output><empty_output><jupyter_text>Python Data Model* The Python data model allow you to design classes that consistently interact with basic language constructs of Python.<jupyter_code>class Vector(object):
    def __init__(self, x=0, y=0, z=0):  
        self.x = x  
        self.y = y  
        self.z = z  
v = Vector(1, 2, 3)  
v.z
v  ## The default string representation
## The special method __repr__allows the definition of custom string representations.

class Vector(Vector):
    def __repr__(self):
        return 'Vector(%r, %r, %r)' % (self.x, self.y, self.z)
v = Vector(1, 2, 3)
v  
print(v)  
## The behavior of abs() and bool() on the Vector class
## can be defined via the special methods __abs__ and __bool__.

class Vector(Vector):
    def __abs__(self):
        return (self.x ** 2 +  self.y ** 2 +
                self.z ** 2) ** 0.5  
    
    def __bool__(self):
        return bool(abs(self))
v = Vector(1, 2, -1)  
abs(v)
bool(v)
v = Vector()  
v  
abs(v)
bool(v)
# The behavior of + and * can be defined through the special methods __add__ and __mul__.

class Vector(Vector):
    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        z = self.z + other.z
        return Vector(x, y, z)  
    
    def __mul__(self, scalar):
        return Vector(self.x * scalar,
                      self.y * scalar,
                      self.z * scalar)  
v = Vector(1, 2, 3)
v + Vector(2, 3, 4)
v * 2
# The special method __len__ gives the length of an object in number of elements.
# The special method __getitem__makes indexing via the square bracket notation possible.


class Vector(Vector):
    def __len__(self):
        return 3  
    
    def __getitem__(self, i):
        if i in [0, -3]: return self.x
        elif i in [1, -2]: return self.y
        elif i in [2, -1]: return self.z
        else: raise IndexError('Index out of range.')
v = Vector(1, 2, 3)
len(v)
v[0]
v[-2]
# causes intentional error
v[3]
# The special method __iter__ defines the behavior during iterations over elements of an object.


class Vector(Vector):
    def __iter__(self):
        for i in range(len(self)):
            yield self[i]
v = Vector(1, 2, 3)
for i in range(3):  
    print(v[i])  # Indirect iteration using index values (via __getitem__).
for coordinate in v:  
    print(coordinate)  # Direct iteration over the class instance (using __iter__).
# Summary

class Vector(object):
    def __init__(self, x=0, y=0, z=0):
        self.x = x
        self.y = y
        self.z = z
    
    def __repr__(self):
        return 'Vector(%r, %r, %r)' % (self.x, self.y, self.z)
    
    def __abs__(self):
        return (self.x ** 2 +  self.y ** 2 + self.z ** 2) ** 0.5
    
    def __bool__(self):
        return bool(abs(self))
    
    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        z = self.z + other.z
        return Vector(x, y, z)
    
    def __mul__(self, scalar):
        return Vector(self.x * scalar,
                      self.y * scalar,
                      self.z * scalar)
    
    def __len__(self):
        return 3
    
    def __getitem__(self, i):
        if i in [0, -3]: return self.x
        elif i in [1, -2]: return self.y
        elif i in [2, -1]: return self.z
        else: raise IndexError('Index out of range.')
            
    def __iter__(self):
        for i in range(len(self)):
            yield self[i]<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup