Reputation: 1093
I am trying to figure out why 'v3' below doesn't work and raises an attribute error. What makes v1 and v2 work and not v3? The code is short and reproducible, and I think it is also simple enough to not need explanation but pls let me know if anything is not clear.
import numpy as np
import pandas as pd
class Example(object):
def __init__(self, ts_df):
self.all_df = ts_df
def simple_av(self, lookback=""):
self.agg = self.all_df.mean(axis=1)
class Example_two(object):
def __init__(self, ts_df, method):
self.ts = ts_df
self.method = method
def apply_method(self, **kwargs):
self.output = self.method(self.ts, **kwargs)
ts = pd.DataFrame(np.random.rand(100,2))
'''v1'''
ex = Example(ts)
ex.simple_av()
print (ex.agg.head())
'''v2'''
func = pd.rolling_mean
ex = Example_two( ts, func)
req_args = dict({'window': 3})
ex.apply_method(**req_args)
print (ex.output.head())
'''v3'''
func = Example.simple_av
ex= Example(ts)
ex.func()
Upvotes: 1
Views: 46
Reputation: 140286
The third example fails because func
exists but ex.func
does not. ex.func
looks up "func"
in the attributes of Example
class and fails.
You could call func
in procedural style, passing ex
as first argument:
func(ex)
which is equivalent to:
ex.simple_av()
(the 2 first examples use a call to a defined method, so it works)
Upvotes: 2