1

I'm experimenting with pandas. I'm trying to create a simple object that represents the data i want to work with. To do so I've written the code below to create an object but I'm getting:

TypeError: test_df() missing 1 required positional argument: 'self

on line 13. I'm not able to figure out what I'm doing wrong. Perhaps something conceptual about the class declaration I'm not getting. Any help is much appreciated.

import pandas as pd

class ICBC():
   def __init__(self, name, path):
       self.name = name
       self.df = pd.read_csv(path)

   def test_df(self):
       print(self.df.info)


mov = ICBC("matisalimba3","z:\devs\py\movimientos.csv")
ICBC.test_df() <- This is line 13
Teoretic
  • 2,483
  • 1
  • 19
  • 28
Matias Salimbene
  • 510
  • 6
  • 19

3 Answers3

5

Once you've created an instance of your class (using ICBC(...)), you need to call the test_df method on the instance, not the class itself.

Change your code so that mov is what you call test_df() on:

import pandas as pd

class ICBC():
   def __init__(self, name, path):
       self.name = name
       self.df = pd.read_csv(path)

   def test_df(self):
       print(self.df.info)


mov = ICBC("matisalimba3","z:\devs\py\movimientos.csv")
mov.test_df()

To further clarify what the error is telling you: when you call a method on an instance in Python, a self argument is automatically passed. However, ICBC is not an instance, so self is not passed. This results in the argument error you've seen.

This behaviour means that you could also do this to call the method:

ICBC.test_df(mov)

However, nobody does this: it's not considered good practice since it makes the code longer and harder to read.

Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
3

Use:

mov = ICBC("matisalimba3","z:\devs\py\movimientos.csv")
mov.test_df()

instead of

ICBC.test_df()

test_df is an instance method, so you need a instance to access it. Your problem is you tried to access the method as it was a class method

rafaelc
  • 57,686
  • 15
  • 58
  • 82
1

test_df is an instance method; you need to call it on an instance of ICBC, not on ICBC itself. Perhaps you meant to write mov.test_df()?

jwodder
  • 54,758
  • 12
  • 108
  • 124