簡體   English   中英

使用 class 的名稱作為 Python 中 function 的參數,使其適用於多種 class 類型

[英]Use name of a class as a parameter of a function in Python to make it work for several class types

我寫了一個 function 來獲取filename ,從文件中讀取信息並從中創建一個Read object。

def read_file(filename):   
  with open(filename, 'r') as filetoread:
        readList = []
        for line in filetoread:
            readList.append(Read(line))
        return readList

這個實現有效。

現在我想概括我的 function 並使其適用於兩種對象/類類型: ReadReference 所以我想使用 class 名稱作為 function 的參數。function 現在獲取filenameclassname名。 它從文件中讀取信息並從中創建一個指定classname名的 object。

我的嘗試看起來像這樣。

def read_file(filename, classname):
  with open(filename, 'r') as filetoread:
        readList = []
        for line in filetoread:
            readList.append(classname(line))
        return readList

我收到 TypeError: 'str' object is not callable。

我的想法是使用這個解決方案:

def str_to_class(classname):
    return getattr(sys.modules[__name__], classname)

資料來源: 將字符串轉換為 Python class object?

我仍然收到錯誤消息(TypeError: getattr(): attribute name must be string)

錯誤: TypeError: 'str' object is not callable. 告訴你你的問題。

要使 object 成為“可調用的”,它必須實現__callable__()魔術方法。 字符串不實現此方法,因此您會收到此錯誤。

可是等等! 你知道什么是 implement __callable__()嗎? 上課!

現在與其嘗試進行一些轉換,不如傳入原始字符。 這個類名是一個token ,將被如此對待。

因此,當致電您的 function 時

使用: read_file("myFile.txt", Read)

而不是: read_file("myFile.txt", "Read")

假設您有一個 class A

class A:
    pass

如果你調用 str 結果應該是<class '__main__.A'>

str(A) == "<class '__main__.A'>"

要獲得 class 名稱,您可以使用__name__方法

str_to_class(Reference.__name__)

或將您的 function 修改為str_or_class_to_class ;-)

暫無
暫無

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

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