簡體   English   中英

如何在python中另一個文件下的另一個類中調用一個方法?

[英]How can I call a method which is in another class under another file in python?

如何從我的python文件中調用同一文件包下另一個fie的另一個類中的方法?

首先,您需要將文件(取決於目錄結構)導入當前腳本中,創建該類的實例,然后在該類中調用該方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM