如何调用pytes的另一个类python中的函数

2024-10-02 00:41:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过键入以下代码来调用我的测试类中CSVDatasource中的方法from ETL.CSVDatasource import CSVDatasource并调用必要的方法,但我收到了类似TypeError: unbound method preprocess_col() must be called with CSVDatasource instance as first argument (got DataFrame instance instead)的错误

http://imgur.com/8sfygtA->;我的编码路径的图像

任何人都可以指导我调用另一个类中的方法,以便我可以调用该方法并在我的测试类中进行测试? 谢谢。在


Tags: 方法instance代码fromimport键入etlcol
1条回答
网友
1楼 · 发布于 2024-10-02 00:41:01

通常,在调用类的方法之前必须创建类的实例。例如

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.'

{{如果我们要在类中创建一个的实例,那么我们就要在这个类中创建一个的实例:

^{pr2}$

但是,如果一个方法不需要self,但您希望将它放在类中,因为在某种意义上,这个方法可能与您的类密切相关。您可以使用修饰符@staticmethod,将其声明为静态方法,就像方法species

这个静态方法可以通过实例或直接通过类调用,如下所示。在

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

根据代码的上下文,您可以选择任何一种方式在类中使用该方法。在

相关问题 更多 >

    热门问题