iT邦幫忙

1

呼叫class的方法,加不加括號的差異

不加括號

class Bank_account():
    def password(self):
        return "password:123"

andy = Bank_account()
print(andy.password)

不加括號,輸出結果

<bound method Bank_account.password of <__main__.Bank_account object at 0x0000012C834FF520>>

加括號

class Bank_account():
    def password(self):
        return "password:123"

andy = Bank_account()
print(andy.password())

加括號,輸出結果

password:123

我的理解是
不加括號是去查看該物件綁定的方法
加括號是去查看該物件的方法內容
想請問各位大大們,我的理解是否有誤,煩請指正

延伸題 @property

class Bank_account():
    @property
    def password(self):
        return "password:123"

andy = Bank_account()
print(andy.password)

andy.password = "password:456"
print(andy.password)

預期的錯誤

password:123
Traceback (most recent call last):File "D:/, line 9, in <module> andy.password = "password:456" AttributeError: can't set attribute

若將第7行加上括號

print(andy.password())
則出現如下錯誤

Traceback (most recent call last):File "D:/", line 7, in <module>
print(andy.password()) TypeError: 'str' object is not callable

想請教為何遇到@property後,就不加括號;表示在讀取屬性時僅能查看?!
再請大大們指正了~
謝謝

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

3
froce
iT邦大師 1 級 ‧ 2021-03-03 14:51:09
最佳解答

加括號就是執行,不加就是本身

def testfun():
    return "test"
    
print(testfun)
print(testfun())

# class的話,加括號就是執行 __init__
# 你把class想成設計圖,沒加括號是設計圖,加了括號是照著設計圖做出的實物
# 做出的實物在程式設計術語中叫 實例(instance)
class TestCls():
	def __init__(self):
		self.v = "test"
		
print(TestCls)
print(TestCls().v)

然後 @property 裝飾子是語法糖
只是讓語意清楚一點。
property翻譯過來叫屬性,是一個唯讀的值,不會讓你做賦值的動作,所以這個裝飾子就幫你綁定,只要呼叫這個屬性就不用畫蛇添足加後面的括號,直接傳回值。
類似java中getter的東西...

我要發表回答

立即登入回答