Matias Salimbene
Matias Salimbene

Reputation: 605

Python class declaration "positional argument" error

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

Upvotes: 1

Views: 996

Answers (3)

Aaron Christiansen
Aaron Christiansen

Reputation: 11807

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.

Upvotes: 5

jwodder
jwodder

Reputation: 57470

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()?

Upvotes: 1

rafaelc
rafaelc

Reputation: 59274

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

Upvotes: 3

Related Questions