簡體   English   中英

python方法返回字符串而不是instancemethod

[英]python method return string rather than instancemethod

我有一個課程和一些方法

class ThisClass:

    def method1(self):
        text1 = 'iloveyou'
        return text1

    def method2(self):
        text2 = self.method1
        print str(text2)

thisObj = ThisClass()
thisObj.method2

我得到的結果是這樣的

<bound method thisclass.method2 of <__main__.thisclass instance at 0x10042eb90>>

我如何打印“ iloveyou”而不是那樣的東西?

謝謝!

缺少方法調用的()。 如果沒有(),則將打印方法對象的字符串表示形式,這對於包括自由函數在內的所有可調用對象也是如此。

確保對所有方法調用都執行此操作( self.method 1和thisObj.method2

class ThisClass:

    def method1(self):
        text1 = 'iloveyou'
        return text1

    def method2(self):
        text2 = self.method1()
        print str(text2)

thisObj = ThisClass()
thisObj.method2()

method2 ,您可以調用函數而不是分配函數指針。

def method2(self):
    text2 = self.method1()
    print text2
    In [23]: %cpaste
    Pasting code; enter '--' alone on the line to stop.
    :class ThisClass:
    :
    :    def method1(self):
    :        text1 = 'iloveyou'
    :        return text1
    :
    :    def method2(self):
    :        text2 = self.method1()
    :        print str(text2)
    :--

    In [24]: thisObj = ThisClass()

    In [25]: thisObj.method2()
    iloveyou

    In [26]: 

暫無
暫無

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

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