首页 > 解决方案 > 如何在 python 的另一个文件下调用另一个类中的方法?

问题描述

如何从我的python文件中调用同一包下另一个文件中另一个类中的方法?

标签: python

解决方案


您首先需要将文件(取决于您的目录结构)导入当前脚本,创建该类的实例,然后在该类中调用该方法;

#Import your other file
import other_file

#Create an instance of the object where your method is
my_obj = NewClass()

#Call the method directly
my_obj.some_method()

您还可以尝试在方法中添加 @staticmethod 以使其可直接调用:

class NewClass:

    @staticmethod
    def some_method():
        print 'Hello'

#call staticmethod add directly 
#without declaring instance and accessing class variables
NewClass.some_method()

推荐阅读