Qing Yong
Qing Yong

Reputation: 127

How to call function that is in the other class python for pytest

I am trying to call the methods in CSVDatasource in my testing class by typing this code from ETL.CSVDatasource import CSVDatasource and to call the necessary methods but I have been receiving errors like TypeError: unbound method preprocess_col() must be called with CSVDatasource instance as first argument (got DataFrame instance instead)

https://i.sstatic.net/rcRoN.jpg -> Image of my coding path

Anyone can guide me on calling out the method in the other class so that I can call the method and do testing in my testing classs? Thanks.

Upvotes: 1

Views: 1140

Answers (1)

Ken T
Ken T

Reputation: 2553

Generally, an instance of the class has to be created before calling the method of the class. For example,

class Person:
    def __init__(self,name):
        self.name=name

    def who(self):
        print 'I am {}'.format(self.name)

    @staticmethod
    def species():
        print 'I am human.'

If we want to call the method who inside the class Person, we have to create an instance of class as follows:

if __name__=='__main__':
    p1=Person('Qing Yong')
    p1.who() #I am Qing Yong

However, if a method doesn't require self but you want to put it inside the class as this method may strongly related to you class in some senses. You may declare it as static method by using the decorator @staticmethod, like the method species

This static method can be called either through instance or through class directly as follows.

if __name__=='__main__':
    p1.species() #I am human.
    Person.species() #I am human.

Depending on the context of your code, you may choose either way to use the method inside your class.

Upvotes: 1

Related Questions