簡體   English   中英

python - 返回 object function / 方法調用的類型

[英]python - returning the type of an object function / method call

我解決了這樣一個問題,我遇到了一個問題。

下面是這句話的內容:使用命令“type”檢查function(打印)返回的object的類型和方法-hello class Person。

這是我到目前為止編寫的代碼:

class Person:
    def __init__(self, name="John", surname="Douglas"):
        self.name= name
        self.surname= surname

        def hello(self):
            print("Hello" + self.name + " " + self.surname)

            Person.hello= "text"
            p = Person()
            p.hello()

我想檢查 Person class 的 Hello 方法返回的 object 的類型。

使用以下命令:

print (type(p.hello()))

然而,這個命令什么也不返回——我不知道它是否能很好地完成這項工作。 我想尋求幫助/建議。

我提前感謝您的每一個答案!

我相信這就是您要實現的目標

class Person:
    def __init__(self, name="John", surname="Douglas"):
        self.name= name
        self.surname= surname

    def hello(self):
        

        #return the string 
        return "Hello " + self.name + " " + self.surname
            
        #Person.hello= "text"
        
#instantiate class Person outside the class
p = Person()
            #p.hello()

print(type(p.hello()))

無論您在 function 中創建了什么,並且想要在外部訪問它,都必須返回它

在檢查其類型之前,您應該有一個返回值,例如SP_ 的 answer 只想補充一點,如果您要檢查某些 if-else 子句中的數據類型,那么isinstance()是比使用type()比較其類型更好的選擇。 喜歡:

p = Person()

if isinstance(p, Person):
    print("do something")

暫無
暫無

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

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