1

If I have a file, foo.py with contents:

import pandas as pd

class Marcher(object):
    def __init__(self, p_path):
        self.p_path = p_path

    p_m = 'ID'

    def first_call(self):
        df_p = pd.read_csv(self.p_path, header=None)
        return df_p

    def p_to_i(self, p):
        pii = p.set_index(self.p_m, drop=False).loc[p[self.p_m]]
        return pii

    m1 = p_to_i(first_call())

What I would like to do with this is something like this:

test = Marcher(p_path='/some/path/to/file.csv')
test.m1

However when I try this I get back an error:

TypeError: first_call() takes exactly 1 argument (0 given)
UberStuper
  • 356
  • 3
  • 17
  • Possible duplicate of [How to decorate a method inside a class?](http://stackoverflow.com/questions/1367514/how-to-decorate-a-method-inside-a-class) – Two-Bit Alchemist Aug 29 '16 at 20:07

2 Answers2

2

why do you want m1 to be a class member variable? just move the call like this:

def __init__(self, path):
    self.path = path
    self.m1 = self.p_to_i(self.first_call())
acushner
  • 9,595
  • 1
  • 34
  • 34
2

The issue is you're trying to call the methods before creating an instance. Take for instance a simple Circle class:

import math

class Circle(object):
    def __init__(self, radius):
        self.radius = radius
    def get_area(self):
        return math.pi * self.radius ** 2
    # You cannot do this because every circle can have a different radius
    # area = get_area()

    # But you can use a property
    @property
    def area(self):
        return self.get_area()

print Circle(2).area
# 12.5663706144
print Circle(10).area
# 314.159265359

Also, sometimes people like to cache property values to avoid re-computing them, that looks something like this:

class Circle(object):
    # ...
    _area = None
    @property area(self):
        if self._area is None:
            self._area = self.get_area()
        return self._area

The downside to this method is that Circle is no longer a dynamic object, you should not update the "radius" attribute once the instance is created because the area is cached and will not get updated.

Bi Rico
  • 25,283
  • 3
  • 52
  • 75